PowerShell: testing for null or empty strings
How $null, empty and whitespace strings behave in an if condition and with IsNullOrEmpty.
In PowerShell, a $null or empty string evaluates to $false in a condition, while a string containing only a space evaluates to $true.
Testing for an empty string
The dedicated .NET method:
[string]::IsNullOrEmpty($str)
Behaviour in an if condition
$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
Combining with -and
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
Notes
- A whitespace-only string is neither
$nullnor empty: to treat it as empty, use[string]::IsNullOrWhiteSpace($str).