,

Powershell: check variable for null

1–2 minutes
31 comments on Powershell: check variable for null
PowerShell 7 Null conditional operators

If you are working a lot with PowerShell parameters and inputs you need to check if variables have the right value and are not “null”. Here is how you can check a PowerShell variable is null. In addition, I am also going to share how you can use the Null conditional operators in PowerShell 7.

PowerShell check variable for null

The normal if -eq “$null” doesn’t work:

if ($varibalename -eq $null) { Write-Host "variable is null" }

Now how you can check that (check if $variablename has $null as value):

if (!$variablename) { Write-Host "variable is null" }

And here if you wanna check if $variablename has any value except $null:

if ($variablename) { Write-Host "variable is NOT null" }

Null assignment and coalescing operators (?? and ??=) in PowerShell 7

If you are running the new PowerShell 7 version, you have new Null conditional operators to make this simpler.

PowerShell 7 Null conditional operators
PowerShell 7 Null conditional operators

With the new PowerShell ?? null coalescing operator to get the value of a statement if it’s not $null or return something else if it is $null. And with the new ??= null conditional assignment operator, you can easily assign a variable a value, but only if the variable is $null.

Here are some examples:

#Variable which is null

$myVariable

#Check variable for null

$myVariable ?? "Is null? True!"

#Check variable for null, and if it is null set the following value

$myVariable ?? "Set the value if null!"

If you want to learn how you can install and update PowerShell 7, check out my blog post.

Conclusion

I hope this helps you to check if your PowerShell variable is null or has a value assigned. If you have any questions, feel free to leave a comment.

31 responses

  1. arnold Avatar
    arnold

    servus :)

    Bitte, wie kanne ich $null, $false, oder $true : Zählen (count)?
    Danke im voraus
    tschüß

    1. Thomas Maurer Avatar

      Zum bsp.

      If (!$variablename){
      $isnull++
      }
      else {
      $isnotnull++
      }

  2. arnold Avatar
    arnold

    sorry das email war fehlerhaft!
    Danke

  3. arnold Avatar
    arnold

    danke! :)

    ich werde es sofort so machen!
    arnold

  4. arnold Avatar
    arnold

    bitte noch mal :)
    ich habe 3 item ( alles sind gut)
    aber:
    in die variable $isnot = 1 und im $gut ist null, warum der unterschied?
    ich wollte eine 3 in der variable $gut haben…
    oder liegt es am switsh?

    vielen dank !
    arnold

    $isnull = 0
    $isnotnull = 0
    If (!$wwwS){$schlecht = $isnull++}
    else {$gut = $isnotnull++
    }
    switch ($wwwS)
    {
    {$_ -ne $gut}{write-host $sk”. Am $date, Für” $_” :” $Calc “Meter/Sekunden”; $sk++;}
    {$_ -eq $schlecht}{write-host $sk”.” $_ ” : Server nicht Erreichbar”; $sk++;}
    }

  5. Jamie Avatar

    Thank you

  6. Volodyak Avatar

    Thank you!!! You are help me!!! :)

  7. Ted Hurlbut Avatar
    Ted Hurlbut

    Thank You!

  8. Dan Avatar

    Merci beaucoup pour ce code.

  9. Steve Culshaw Avatar
    Steve Culshaw

    Excellent reminder

  10. Aaron Butler Avatar
    Aaron Butler

    Thanks! Clear and helpful.

  11. Luke Wilkins Avatar
    Luke Wilkins

    Great tip – nice efficient code.

  12. Nitin K Avatar

    Thanks buddies!! This post was very helpful to me.

  13. Alexander Avatar
    Alexander

    These constructions won’t work if variable is $false or 0 etc.
    If you really need to ensure that variable is null or not you can use this:
    [Object]::ReferenceEquals($var, $null)

  14. xoepa Avatar

    Merci beaucoup !

  15. Joachim Tausch Avatar
    Joachim Tausch

    @ Thomas Maurer,
    do you mind editing your original post correcting the bad mistake that Alexander pointed out in his comment on 2015-04-01 ? — It doesn’t bear thinking that someone writing critical code is trusting in your original advice not reading down to the 18th comment…

  16. Eugene Avatar

    in my the case it’s does not work

    $NumRecPoint = 0
    $NumRecPoint -eq $null
    !$NumRecPoint

    False
    True

  17. Phil Avatar

    (!$variableName) will also return true if $variableName is False, or has been set to 0.

    A better way to check if something is null is to compare it to $null:

    if ($variableName -eq $null) { Write-Host “variable is null” }
    if ($variableName -ne $null) { Write-Host “variable is not null” }

    Note that $null is a magic variable that will always be set to null.

  18. Guilherme Avatar
    Guilherme

    I believe that for -errorvariable this is perfect. Never saw an error returning a number or “false” before, but I had many problems when using if ($variable -eq $null). The script just hangs once in a while. So, for errorvariable, I realy recoment using if($variable) or if(!$variable). It works all the time.

  19. Ano Avatar

    You had stated it incorrectly as ‘The normal if -eq “$null” doesn’t work:’; if you had used a null string to compare it would have worked:

    [String] ${stVar} = ${Null}
    PS D:\Users\srhoads\Documents\Dev\PowerShell> if ( “${Null}” -eq ${stVar} ) {write-host “True”} else {write-host “False”}
    Returns: True

    You can’t compare a string containing a Null to a Null (you have to use a null string “${Null}”).

  20. Ian Avatar

    Thanks for this, really useful to know, especially for a beginer.

  21. rotem Avatar

    simply use this check statement after the match check

    $result = $t -match “‘(?[a-zA-Z]+)”
    if(-not $result)
    {
    continue
    }

  22. cividan Avatar

    Thanks alot this was very helpfull to me as my check for null were not working in my script.

  23. PowerPete Avatar
    PowerPete

    $foo = $null

    # Confused intent of null check as type inference takes place
    # this Returns $True and the output!
    if(!$foo) {
    Write-Host ‘This runs’
    }

    See: https://rencore.com/blog/powershell-null-comparison/

  24. antonio Avatar
    antonio

    maybe if ($varibalename -eq $null) { Write-Host “variable is null” } does not work because of the typo?
    $varibalename should be $variablename

  25. Marco Avatar
    Marco

    does it work for Boolean variables?
    I guess no!

  26. Fernando Avatar

    Thanks!

    1. Thomas Maurer Avatar

      You’re welcome :)

  27. Ruszlán Gaszanov Avatar
    Ruszlán Gaszanov

    There is a very simple way to test is a PowerShell variable is defined and not null:

    if ($var -is [object]) { ‘$var is defined and not null’ } else { ‘$var is undefined or not null’}

    This is works because all valid PowerShell values other than $null are instances of the .NET System.Object class

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.