Best way to check if an PowerShell Object exist?

223,450

Solution 1

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

Solution 2

You can also do

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

Solution 3

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

Solution 4

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 !

Solution 5

Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System.Object] will be true for any possible non-null value. (In all cases, it will be false for any null-value.)

My value is nothing if not an object.

Share:
223,450
LaPhi
Author by

LaPhi

Hello my name is Lars, I´m a Computer Science student and I work in the IT industry. My focus is PowerShell, SharePoint, Office 365, SQL, Security.

Updated on September 01, 2021

Comments

  • LaPhi
    LaPhi over 2 years

    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 -ComObject InternetExplorer.Application
    $ie.Navigate("http://www.stackoverflow.com")
    $ie.Visible = $true
    
    $ie -ne $null #Are there better options?