其他答案解决了问题的主旨,但只是对这部分发表评论......
PS C:\> [array]$foo = @("bar")
PS C:\> $foo -eq $null
PS C:\>
“-eq $null”怎么会没有结果?它要么是 $null,要么不是。
一开始会让人困惑,但是是给你$foo -eq $null的结果,只是结果没有可显示的表示。
由于$foo 持有一个数组,$foo -eq $null 的意思是“返回一个包含$foo 的元素等于$null 的数组”。 $foo 的任何元素是否等于$null?不,所以$foo -eq $null 应该返回一个空数组。这正是它的作用,问题是当控制台上显示一个空数组时,您会看到...什么都没有...
PS> @()
PS>
数组仍然存在,即使你看不到它的元素...
PS> @().GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @().Length
0
我们可以使用类似的命令来确认$foo -eq $null 正在返回一个我们无法“看到”的数组...
PS> $foo -eq $null
PS> ($foo -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($foo -eq $null).Length
0
PS> ($foo -eq $null).GetValue(0)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($foo -eq $null).GetValue(0)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
请注意,我调用的是Array.GetValue method,而不是使用索引器(即($foo -eq $null)[0]),因为后者为无效索引返回$null,并且无法将它们与恰好包含@987654338 的有效索引区分开来@。
如果我们在包含$null 元素的数组中测试$null,我们会看到类似的行为...
PS> $bar = @($null)
PS> $bar -eq $null
PS> ($bar -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($bar -eq $null).Length
1
PS> ($bar -eq $null).GetValue(0)
PS> $null -eq ($bar -eq $null).GetValue(0)
True
PS> ($bar -eq $null).GetValue(0) -eq $null
True
PS> ($bar -eq $null).GetValue(1)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($bar -eq $null).GetValue(1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
在这种情况下,$bar -eq $null 返回一个包含一个元素 $null 的数组,该元素在控制台上没有视觉表示...
PS> @($null)
PS> @($null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @($null).Length
1