Since I'm not sure when powershell iterates over $null
and when it doesn't, I need to check if the variable is $null
or not before each iteration. Maybe someone can explain to me why this is the case and how to handle arrays correctly.
Whenever I iterate over an array and use Where-Object
to limit the results to nothing, the result I get is a $null
object which cannot be iterated over (correct behavior).
> $array = @(1,2,3) | Where-Object { $false }
> $null -eq $array
True
> $array | ForEach-Object { "begin" } { $null -eq $_ } { "end" }
begin
end
If I initialize the array to $null
, it is treated as an iterable value (not quite what you would expect). This behavior seems to result from Powershell interpreting non-arrays as single-entry arrays.
> $array = $null
> $array | ForEach-Object { "begin" } { $null -eq $_ } { "end" }
begin
True
end
The same thing happens when I get the array from a function.
> class MyA { MyA() {} [object]getArray() { return (@(1,2,3) | Where-Object { $false }) }}
> $mya=[MyA]::new()
> $mya.getArray() | ForEach-Object { "begin" } { $null -eq $_ } { "end" }
begin
True
end
The only solution seems to be to pre-check the array for $null
each time and replace it with an empty array.
> if ($null -eq $array) { $array = @() }
> $array | ForEach-Object { "begin" } { $null -eq $_ } { "end" }
begin
end
Does anyone have an explanation or another solution to this problem?