在处理 $null 比较时,请参阅此 SO Q&A:
在 PowerShell 中,为什么 $null -lt 0 = $true?那可靠吗?
我目前没有 VMware,但在我的小型 Hyper-V 实验室中,运行以下命令会提供显示的结果:
Try
{
(
Get-VM |
Where-Object -Property FloppyDrive -eq $null |
Select Name, FloppyDrive -ErrorAction SilentlyContinue
).Count
}
Catch { Write-Warning -Message 'No no records returned'}
# Results
<#
4
#>
Try
{
(
Get-VM |
Where-Object -Property FloppyDrive -ne $null |
Select Name, FloppyDrive -ErrorAction SilentlyContinue
).Count
}
Catch { Write-Warning -Message 'No no records returned'}
# Results
<#
WARNING: No no records returned
#>
使用这些结果也是一样的。
Try
{
(
Get-VM |
Where-Object -Property FloppyDrive -Match $null |
Select Name, FloppyDrive -ErrorAction SilentlyContinue
).Count
}
Catch { Write-Warning -Message 'No no records returned'}
Try
{
(
Get-VM |
Where-Object -Property FloppyDrive -NotMatch $null |
Select Name, FloppyDrive -ErrorAction SilentlyContinue
).Count
}
Catch { Write-Warning -Message 'No no records returned'}
在您的用例中,请尝试以下重构:
(Get-VM).Name |
foreach {
if ((Get-VM -Entity $PSitem | Get-Annotation -CustomAttribute 'Backup') -eq $null)
{ "$PSItem - Attribute doesnt have a value" }
else {"$PSItem - Attribute has a value assigned"}
}
或者...
(Get-VM).Name |
foreach {
if ((Get-VM -Entity $PSitem | Get-Annotation -CustomAttribute 'Backup') -Match $null)
{ "$PSItem - Attribute doesnt have a value" }
else {"$PSItem - Attribute has a value assigned"}
}