我想了解@()數組構造函數的行爲,並且遇到了這個非常奇怪的測試。爲什麼空的PowerShell管道與空值不一樣?
看來,空管的值是「不完全」同爲$ null,即使它是當量$空
$x = 1,2,3,4 | ? { $_ -ge 3 }
$y = 1,2,3,4 | ? { $_ -ge 5 }
$z = $null
"x is $x"
"y is $y"
"z is $z"
if ($x -eq $null) {'x is null'} else {'x NOT null'}
if ($y -eq $null) {'y is null'} else {'y NOT null'}
if ($z -eq $null) {'z is null'} else {'z NOT null'}
$ax = @($x)
$ay = @($y)
$az = @($z)
"ax.length = " + $ax.length
"ay.length = " + $ay.length
"az.length = " + $az.length
"az[0].GetType "
$az[0].GetType()
產生以下輸出
x is 3 4
y is
z is
x NOT null
y is null
z is null
ax.length = 2
ay.length = 0
az.length = 1
az[0].GetType
You cannot call a method on a null-valued expression.
At line:18 char:5
+ $az[0].GetType()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
所以$ az數組長度爲1,$ az [0]爲$ null。
但真正的問題是:$ y和$ z都可能是-eq $ null,但是當我用@(...)構造數組時,那麼一個數組是空的,另一個數組是空的包含一個$ null元素?
優秀的描述。我驚呆了,有不止一個null。進一步谷歌搜索後,我發現第三個:System.Management.Automation.Language.NullString。由於所有這些空值都是-eq $ null,我怎樣才能真正測試哪個null在變量中? (不是這是一個常見的要求!) –
特殊的空值不是什麼新東西,例如有System.DBNull.Value。不過,PowerShell並不會將這些其他特殊的空值視爲null。 [NullString] :: Value -ne $ null。 –
感謝您使用Test-IsAutomationNull進行更新。我發現你需要運行一個管道,檢測它不處理任何東西,並得出結論:它必須收到一個AutomationNull。我想這就是當語言開始使用魔法值時你得到的。乾杯。 –