Why do the following 3 lines run without error from the PowerShell prompt, but return an error when run in a script (foo.ps1)? In both cases, $b -eq $null
returns $true
and $b.GetType()
returns an error for invoking on $null
, but there is something different about the $b
in the interactive session.
$a = 1,2,3
[array]$b = $a | where {$false}
$b | where {$_.GetType()}
When run as script, the last line returns
You cannot call a method on a null valued expression.
I ran into this during ill-fated attempts to prevent array unrolling. Removing [array]
makes the error go away, and I'll move on to trying to better understand the unrolling rules (I want $b
to be an empty array, not $null
), but I'd like to understand the reason for the difference here.