No, the first example is not just a legacy. To create a PowerShell function that uses an array parameter and accepts an input stream, you need to do some work.
I even guess that the second example does not work. At least I couldn't get it to work.
Take this example ...
function PipelineMadness() { [cmdletbinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline=$true)] [int[]] $InputArray ) Write-Host ('$InputArray.Count {0}' -f $InputArray.Count) Write-Host $InputArray Write-Host ('$input.Count {0}' -f $input.Count) Write-Host $input if($input) { Write-Host "input is true" } else { Write-Host "input is false" } }
results...
PS C:\Windows\system32> 1..5 | PipelineMadness $InputArray.Count 1 5 $input.Count 5 1 2 3 4 5 input is true PS C:\Windows\system32> PipelineMadness (1..5) $InputArray.Count 5 1 2 3 4 5 $input.Count 1 input is false
Note that when using the pipeline, the $InputArray
variable represents a single value of 5 ...
Now with BEGIN and PROCESS blocks
function PipelineMadnessProcess() { [cmdletbinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline=$true)] [int[]] $InputArray ) BEGIN { Write-Host 'BEGIN' Write-Host ('$InputArray.Count {0}' -f $InputArray.Count) Write-Host $InputArray Write-Host ('$input.Count {0}' -f $input.Count) Write-Host $input if($input) { Write-Host "input is true" } else { Write-Host "input is false" } } PROCESS { Write-Host 'PROCESS' Write-Host ('$InputArray.Count {0}' -f $InputArray.Count) Write-Host $InputArray Write-Host ('$input.Count {0}' -f $input.Count) Write-Host $input if($input) { Write-Host "input is true" } else { Write-Host "input is false" } } }
Now this is where it gets weird
PS C:\Windows\system32> 1..5 | PipelineMadnessProcess BEGIN $InputArray.Count 0 $input.Count 0 input is false PROCESS $InputArray.Count 1 1 $input.Count 1 1 input is true PROCESS $InputArray.Count 1 2 $input.Count 1 2 input is true ... PROCESS $InputArray.Count 1 5 $input.Count 1 5 input is true
The BEGIN block contains no data at all. And the process block works well if you have foreach
, as in the example that it will actually work, but it will run foreach
with 1 input X times. Or, if you pass in an array, it will run foreach
once with a full set.
So, I assume that technically this example will work, but it may not work as you expect.
Also note that even if the BEGIN block had no data, the function passed the syntax check.