How can I check if a string is null or empty in PowerShell?
Solution 1
You can use the IsNullOrEmpty
static method:
[string]::IsNullOrEmpty(...)
Solution 2
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
Solution 3
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
Solution 4
If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty
as you can see in this example:
Function Test-Something
{
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
#stuff todo
}
Solution 5
Personally, I do not accept a whitespace ($STR3) as being 'not empty'.
When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.
I find this is the best way to accomplish it:
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
Empty
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
Empty
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
Empty!! :-)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
Not empty
vel
Updated on September 27, 2021Comments
-
vel over 2 years
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.