This bit me once in the past, and again today. What a waste of time!
PowerShell functions can’t have a parameter called input
. No error is thrown when you define the parameter thus, it just doesn’t work that’s all.
1 2 3 4 5 6 7 8 9 10 |
# defining the function PS> function Test ($input) { "Hello $input" } # notice the parameter is ignored PS> Test -input "ABC" Hello # trying with a different parameter name PS> function Test2 ($output) { "Hello $output" } # works! PS> test2 -output "ABC" Hello ABC |
What about if I try constraining the parameter type?
1 2 3 4 5 6 7 8 9 |
PS> function Test ([int]$input) { "Hello $input" } PS> Test -input 1 Test : Cannot convert the "System.Collections.ArrayList+ArrayListEnumeratorSimple" value of type "System.Collections.ArrayList+ArrayListEnumeratorSimple" to type "System.Int32". At line:1 char:1 + Test -input 1 + ~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Test], PSInvalidCastException + FullyQualifiedErrorId : ConvertToFinalInvalidCastException,Test |
Still the same, just that I get a weird error too. Looks like the default parameter input
is of type ArrayList
.
Update: Later I learnt that all PowerShell functions have a default variable called $input
(similar to the default variable $args
). When the function accepts input from a pipeline this variable is what holds the input.
1 2 3 4 5 6 |
PS> function Test ($input) { "Hello $input" } PS> Test -input "Boo" Hello # notice it works when given via pipeline PS> "Boo" | Test Hello Boo |