How can I check if a string is null or empty in PowerShell?
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
You can use the IsNullOrEmpty
static method:
[string]::IsNullOrEmpty(...)
In addition to [string]::IsNullOrEmpty
in order to check for null or empty you can cast a string to a Boolean explicitly or in Boolean expressions:
$string = $null[bool]$stringif (!$string) { "string is null or empty" }$string = ''[bool]$stringif (!$string) { "string is null or empty" }$string = 'something'[bool]$stringif ($string) { "string is not null or empty" }
Output:
Falsestring is null or emptyFalsestring is null or emptyTruestring is not null or empty