How to check for null and empty characters in variables in PowerShell

Method 1

Put a variable in the conditional statement of the if statement.

Example

# Example 1
PS> $var = $null
PS> if($var){"not null or empty"}else{"null or empty"}
null or empty
# Example 2
PS> $var = ""
PS> if($var){"not null or empty"}else{"null or empty"}
null or empty
# Example 3
PS> $var = "a"
PS> if($var){"not null or empty"}else{"null or empty"}
not null or empty

Method 2

Use [String]::IsNullOrEmpty().

Example

PS> $var = $null
PS> [String]::IsNullOrEmpty($var)
True
PS> $var = ""
PS> [String]::IsNullOrEmpty($var)
True
PS> $var = "a"
PS> [String]::IsNullOrEmpty($var)
False

Method 3

Cast in bool.

Example

PS> $var = $null
PS> [bool]$var
False
PS> $var = ""
PS> [bool]$var
False
PS> $var = "a"
PS> [bool]$var
True