Best way to check if an PowerShell Object exist? Best way to check if an PowerShell Object exist? powershell powershell

Best way to check if an PowerShell Object exist?


I would stick with the $null check since any value other than '' (empty string), 0, $false and $null will pass the check: if ($ie) {...}.


You can also do

if ($ie) {    # Do Something if $ie is not null}


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 = $nulltry {    $ie = New-Object -ComObject InternetExplorer.Application}catch {    Write-Warning $_}# check and continuationif ($ie -ne $null) {    ...}