Best way to check if an PowerShell Object exist?

前端 未结 7 2148
无人及你
无人及你 2020-12-10 10:19

I am looking for the best way to check if a Com Object exists.

Here is the code that I have; I\'d like to improve the last line:

$ie = New-Object -Co         


        
7条回答
  •  隐瞒了意图╮
    2020-12-10 10:42

    What all of these answers do not highlight is that when comparing a value to $null, you have to put $null on the left-hand side, otherwise you may get into trouble when comparing with a collection-type value. See: 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"
    }
    

    The above block is (unfortunately) executed. What's even more interesting is that in Powershell a $value can be both $null and not $null:

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

    So it is important to put $null on the left-hand side to make these comparisons work with collections:

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

    I guess this shows yet again the power of Powershell !

提交回复
热议问题