How can I check if a string is null or empty in PowerShell?
You can use the IsNullOrEmpty
static method:
[string]::IsNullOrEmpty(...)
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
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]$string
if (!$string) { "string is null or empty" }
$string = ''
[bool]$string
if (!$string) { "string is null or empty" }
$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }
Output:
False
string is null or empty
False
string is null or empty
True
string is not null or empty