Powershell: Check variable for null

Powershell: Check variable for null

If your working a lot with parameters and inputs you need to check if variables have the right value and are not “null”.

You can check that (check if $variablename has $null as value):

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

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

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

 

powershell-null

vovando Avatar

3 responses to “Powershell: Check variable for null”

  1. Nesith Weerasinghe Avatar
    Nesith Weerasinghe

    This does not work if $variablename = 0

    1. moosenl Avatar
      moosenl

      That’s not the same as an empty variable..

  2. Nesith Weerasinghe Avatar
    Nesith Weerasinghe

    my point exactly, for the first if statement it will say your variable is null , and for the second if statement it will print nothing

    test out put below, hence this is not a complete test as it incorrectly told me a variable was null.

    $variable = 0

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

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

    variable is null

Leave a Reply

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