How can I check if a string is null or empty in PowerShell?

pencilCake picture pencilCake · Dec 6, 2012 · Viewed 554.1k times · Source

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell?

I could not find it so far and if there is a built-in way, I do not want to write a function for this.

Answer

Keith Hill picture Keith Hill · Dec 6, 2012

You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty