Checking for a Null or Empty String

It is quite common when writing PowerShell script that you need to check if a variable, which is supposed to be a string, is not null or empty before processing it.  I see many folks use [string]::IsNullOrEmpty($str) including myself in the past.  But it appears that this approach is unnecessary and requires more typing.  In PowerShell you can easily test for a non-null or empty string like so:
 
1> function IsNullOrEmpty($str) {if ($str) {"String is not empty"} else {"String is null or empty"}}
 
Now let’s double check that this is working as expected:
 
2> $str = $null
3> IsNullOrEmpty $str
String is null or empty
 
4> $str = ”
5> IsNullOrEmpty $str
String is null or empty
 
6> $str = ‘hi’
7> IsNullOrEmpty $str
String is not empty
 
So as we can see.  It is enough to do a simple check "if ($str)" on a string to make sure it is not null nor empty.
 
Update 4/25/2008: Bill points out in a comment that you do need to still explicitly test for [DBNull]::Value if you work with data from a database.
Advertisements
This entry was posted in PowerShell. Bookmark the permalink.

11 Responses to Checking for a Null or Empty String

  1. Bill says:

    I read your post and thought..  Cool.  that makes a lot of sense.. and quickly threw away my IsNullOrEmpty function.
     
    But, if($str) didn\’t seem to work in all cases.
     
    After some checking, remembered that objects from the database are not $Null, they are [DBNull]::Value.
     
    So I re-built my function and added.  if ($str -eq [DBNull]::Value){ return $True;}
     
    Not technically a string, but keeps me from having to check the value twice.
     
    Bill
     
     
     

  2. Keith says:

    Bill, good point.  I don\’t do much with databases so the DBNull issue didn\’t occur to me. Thanks for pointing that out.

  3. Thanks Bill,
    When loading a CSV and testing a column for existance, I was getting back unexpected results (empty columns being returned). I found your DBNULL test worked…
    EG:
    $csv = import-csv “.\links.csv”
    foreach ($line in $csv)
    if ($($line.Column1) -ne [DBNull]::Value)
    {
    $link = $($line.Column1)
    write-host “$link”
    }

    Thanks,
    SebastianRizzo

  4. joey says:

    New to powershell, but figured I’d share my findings. This (!$var) also works for an empty value in a CSV. Kinda a long example, but it’s what I was working on.

    ====CSV FILE====
    id,firstname,lastname
    user-a,,lastname-a
    user-b,firstname-b,lastname-b
    user-c,firstname-c,

    ====CODE====
    # CSV file location
    $CSVFile = Import-Csv -path “c:\scripts\logs\ad_update.txt”

    foreach ($account in $CSVFile)
    {

    Write-host “$($account.id),$($account.firstname),$($account.lastname)”

    if (($account.firstname) -and ($account.lastname))
    {
    Write-Host “First and Last Name Change for account: $($account.id)”
    }

    if (($account.firstname) -and (!$account.lastname))
    {
    Write-Host “First Name Change for account: $($account.id)”
    }

    if ((!$account.firstname) -and ($account.lastname))
    {
    Write-Host “Last Name Change for account: $($account.id)”
    }
    Write-Host
    }

    ====OUTPUT====
    user-a,,lastname-a
    Last Name Change for account: user-a

    user-b,firstname-b,lastname-b
    First and Last Name Change for account: user-b

    user-c,firstname-c,
    First Name Change for account: user-c

  5. I just think it is ok only for strings not bools

    • rkeithhill says:

      Not sure I follow you. Booleans work even better because no coercion is involved.

      $abool = $true
      if ($abool) { “This should be output” }

      Works just as well as:

      if ($abool -eq $true) { “This should be output” }

  6. techibee.com says:

    You check if a variable is NULL, EMPTY, or having whitespaces by using system.string dotnet class. Check http://techibee.com/powershell/check-if-a-string-is-null-or-empty-using-powershell/1889 for examples.

    • rkeithhill says:

      Yes, if you also need to check for a string containing only whitespace then [string]::IsNullOrWhitespace($str) is the way to go. However, in my experience with PowerShell script, I’ve rarely needed the extra “whitespace” test.

      • Doug Wagner says:

        Had good success with trim() and trimEnd() methods on a string.
        Saw unexpected errors looping thru a list of PC names due to trailing space characters. I introduced the trailing spaces by “cleaning up” my PC list with a programming editor. Now I don’t trust “human generated” input before I use trim() on it.

  7. Pingback: Powershell Quick Parameters for Scripts | Voice of the DBA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s