$ null / empty interaction vs script difference

Why do the following three lines start without errors from the PowerShell prompt, but return an error when launched in script (foo.ps1)? In both cases, it $b -eq $nullreturns $trueand $b.GetType()returns an error to call in $null, but there is something else in the interactive session $b.

$a = 1,2,3
[array]$b = $a | where {$false}
$b | where {$_.GetType()}

When run as a script, the last line returns

You cannot call a method for an expression with a null value.

I came across this during the ill-fated attempts to prevent the expansion of arrays. Deleting [array]makes the error go away, and I will move on to better understand the expansion rules (I want it to $bbe an empty array, not $null), but I would like to understand the reason for the difference here.

+4
source share
2 answers

There is a perfect explanation

  1. By typing [array], you indicate that the variable will be strongly typed. I suspect this line in .NET code, throws an exception, because it needs a type as a variable ... http://referencesource.microsoft.com/#mscorlib/system/array.cs,72
+1
source

If you use it from ISE or from interactive, variables are saved. In your examples, I'm not sure why you are using / Where-Objectinstead . Working on what I think you are trying to do:%ForEach-Object

$a = @(1, 2, 3)
[Array]$b
$a | % { $b += $_ }
$b | % { $_.GetType() }
0
source

Source: https://habr.com/ru/post/1679731/


All Articles