Best way to check if an PowerShell Object exist?

前端 未结 7 2172
无人及你
无人及你 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:45

    In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?

    Only in the code like below we need some checks (explicit comparison with $null is the best):

    # 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) {
        ...
    }
    

提交回复
热议问题