检查PowerShell对象是否存在的最佳方法是什么?

LaP*_*Phi 85 powershell null object powershell-2.0

我正在寻找检查Com对象是否存在的最佳方法.

这是我的代码; 我想改进最后一行:

$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate("http://www.stackoverflow.com")
$ie.Visible = $true

$ie -ne $null #Are there better options?
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 104

我会坚持$null检查,因为除了''(空字符串)之外的任何值0,$false并且$null将通过检查:if ($ie) {...}.

  • 使用 if ($val){...} 对于布尔值更好 所有其他检查应该是 if ($val -ne $null){..} 我自己测试过。TY @基思·希尔 (2认同)

rav*_*nth 60

你也可以

if ($ie) {
    # Do Something if $ie is not null
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个选项和它的取反`if(-not $ ie){#如果$ ie不存在/是假的,做点事}` (4认同)

Rom*_*min 15

在您的特定示例中,可能根本不需要执行任何检查.这可能会New-Object返回null吗?我从未见过这个.如果出现问题,该命令应该失败,并且不会执行示例中的其余代码.那我们为什么要做那个检查呢?

只有在下面的代码中我们需要一些检查(与$ null的显式比较是最好的):

# we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 然后,当我们需要检查$ null时,代码不会显示. (2认同)

小智 5

所有这些答案没有强调的是,在将值与$ null比较时,必须将$ null放在左侧,否则在与collection-type值进行比较时可能会遇到麻烦。参见:https : //github.com/nightroman/PowerShellTraps/blob/master/Basic/Comparison-operators-with-collections/looks-like-object-is-null.ps1

$value = @(1, $null, 2, $null)
if ($value -eq $null) {
    Write-Host "$value is $null"
}
Run Code Online (Sandbox Code Playgroud)

上面的代码块(不幸的是)被执行。更有趣的是,在Powershell中,$ value既可以是$ null,也可以不是$ null:

$value = @(1, $null, 2, $null)
if (($value -eq $null) -and ($value -ne $null)) {
    Write-Host "$value is both $null and not $null"
}
Run Code Online (Sandbox Code Playgroud)

因此,将$ null放在左侧非常重要,以使这些比较可与集合一起使用:

$value = @(1, $null, 2, $null)
if (($null -eq $value) -and ($null -ne $value)) {
    Write-Host "$value is both $null and not $null"
}
Run Code Online (Sandbox Code Playgroud)

我想这再次显示了Powershell的强大功能!

  • 令人惊讶的是这个答案没有得到更多的支持,因为它包含将“$null”放在左侧的**关键**细节 (3认同)