POSTS
PowerShell advanced parameter behavior unexpected
I have been experimenting with parameter values from the pipeline and the processing behavior is slightly different when using piplines vs. parameterized values. It is easy enough to work around, but I wanted to make sure and explain the issue and one workaround.
The standard way of using a pipeline parameter is to do something like this:
param
(
[parameter(Mandatory=$true,
ValueFromPipeLine=$true)]
[String[]]$item
)
In cases where you accept input from the pipeline or a single item as an input parameter this works fine.
"one","two" | .\AdvancedParameterScript.ps1
.\AdvancedParameterScript.ps1 -item "one"
However, it breaks when you try to specify an array of items using the parameter syntax. This happens because the process block happens once with the ‘item’ parameter containing an array of all of the values.
.\AdvancedParameterScript.ps1 -item "one"
Here is a simple script that I used to test it.
|
|
|
|
You can see that in the second case the parameter is being assigned an array containing both values. The examples of pipelined input I have seen do not appear to expect this use case because most of them would fail.
Since the pipeline input is being sent to the PROCESS block as an array of length 1 we can easily work around the differences by using a foreach loop. It may seem silly to do this when expecting a single item, but it makes the processing behavior the same in all three cases.
|
|
And the output:
|
|