PowerShell IsNullOrEmpty: Check if a Variable Is Null or Empty

To check if a string is null or empty in PowerShell, use [string]::IsNullOrEmpty($value). It returns True for $null and for an empty string, and False for anything else:

foreach ($value in 'Alice', '', $null) {
    '[{0}] is null or empty: {1}' -f $value, [string]::IsNullOrEmpty($value)
}

Output:

[Alice] is null or empty: False
[] is null or empty: True
[] is null or empty: True
PowerShell IsNullOrEmpty checks a string for null or empty
IsNullOrEmpty on a name, an empty string and $null (PowerShell 7)

That covers most scripts. Below I compare it with the other null checks, since each one treats values like spaces and 0 differently.

I ran every example in PowerShell 7.6 and Windows PowerShell 5.1. The results matched, except for two operators that only exist in PowerShell 7.

Which null or empty check should I use?

I ran four common checks against the same values. Here’s what each one returns:

$cases = [ordered]@{
    '$null' = $null; "''" = ''; "' '" = ' '; "'0'" = '0'
    '0' = 0; '@()' = @(); "'False'" = 'False'; '$false' = $false
}

'{0,-8} {1,-14} {2,-19} {3,-6} {4}' -f 'Value', 'IsNullOrEmpty', 'IsNullOrWhiteSpace', 'if()', '$null -eq'
foreach ($c in $cases.GetEnumerator()) {
    '{0,-8} {1,-14} {2,-19} {3,-6} {4}' -f $c.Key,
        [string]::IsNullOrEmpty($c.Value), [string]::IsNullOrWhiteSpace($c.Value),
        [bool]$c.Value, ($null -eq $c.Value)
}

Output:

Value    IsNullOrEmpty  IsNullOrWhiteSpace  if()   $null -eq
$null    True           True                False  True
''       True           True                False  False
' '      False          True                True   False
'0'      False          False               True   False
0        False          False               False  False
@()      True           True                False  False
'False'  False          False               True   False
$false   False          False               False  False
PowerShell IsNullOrEmpty, IsNullOrWhiteSpace, if and $null -eq compared
Four checks against eight values (Windows PowerShell 5.1)

A few results are easy to miss. A plain if ($value) treats 0 and $false as empty, but the text ‘0’ and ‘False’ as filled in. $null -eq is True only for $null.

Use thisWhen you want to catch
$null -eq $valueOnly a missing value
[string]::IsNullOrEmpty($value)Missing or empty text
[string]::IsNullOrWhiteSpace($value)Missing, empty or blank text, like user input
$items.Count -eq 0An empty array or hashtable

IsNullOrWhiteSpace for user input

A value of only spaces isn’t empty, so IsNullOrEmpty lets it through. IsNullOrWhiteSpace catches it:

$city = '   '

"IsNullOrEmpty:      $([string]::IsNullOrEmpty($city))"
"IsNullOrWhiteSpace: $([string]::IsNullOrWhiteSpace($city))"

Output:

IsNullOrEmpty:      False
IsNullOrWhiteSpace: True

For names, addresses and anything else people type, I use IsNullOrWhiteSpace. IsNullOrEmpty vs IsNullOrWhiteSpace compares the two in more detail.

Check if a variable is null: put $null on the left

Write $null -eq $value, not $value -eq $null. When the value is an array, the second form filters the array instead of testing it:

$values = @('Austin', $null, $null)

if ($values -eq $null) { '$values -eq $null says: null' }
if ($null -eq $values) { '$null -eq $values says: null' } else { '$null -eq $values says: not null' }

Output:

$values -eq $null says: null
$null -eq $values says: not null
PowerShell $null on the left side of a comparison with an array
The same test gives two different answers (PowerShell 7)

$values -eq $null returned the two $null items, and a list with two items counts as True. Microsoft’s Everything you wanted to know about $null explains this in depth.

Check if a variable exists

A variable you never set also reads as $null. To tell “not set” apart from “set to null”, check the Variable: drive:

$city = 'Denver'

"city exists:    $(Test-Path -Path Variable:\city)"
"country exists: $(Test-Path -Path Variable:\country)"

Output:

city exists:    True
country exists: False

Catch unset variables with strict mode

Strict mode turns a typo in a variable name into an error instead of a silent $null:

Set-StrictMode -Version Latest

try {
    "Country: $country"
}
catch {
    "Strict mode stopped it. $($_.Exception.Message)"
}

Output:

Strict mode stopped it. The variable '$country' cannot be retrieved because it has not been set.

I turn it on at the top of longer scripts. It catches mistakes that a null check would hide.

If null, then use an empty string

To replace $null with an empty string in Windows PowerShell 5.1, cast it to [string] or use a plain if:

$middleName = $null

$display = [string]$middleName
"Cast to string:  [$display]"

if ($null -eq $middleName) { $middleName = '' }
"After the if:    [$middleName]"

Output:

Cast to string:  []
After the if:    []

PowerShell 7 adds the null-coalescing operators. ?? gives a fallback value, and ??= assigns one only when the variable is null:

$phone = $null
"Phone: [$($phone ?? 'not provided')]"

$email = $null
$email ??= 'none@example.com'
"Email: [$email]"

Output in PowerShell 7:

Phone: [not provided]
Email: [none@example.com]

Both fail with a parser error in 5.1, so only use them in scripts that run on PowerShell 7. about_Operators covers them and the ternary operator.

Check if an array or hashtable is empty

For collections, check .Count. It’s 0 for an empty array, an empty hashtable and even $null:

$orders = @()
$settings = @{}

"Orders empty:   $($orders.Count -eq 0)"
"Settings empty: $($settings.Count -eq 0)"
"Null count:     $($null.Count)"

Output:

Orders empty:   True
Settings empty: True
Null count:     0

Checking if an array is empty has more examples.

Stop empty values at the function parameter

Instead of checking inside a function, let PowerShell reject empty values before the function runs:

function New-Customer {
    param(
        [ValidateNotNullOrEmpty()]
        [string]$Name
    )
    "Created customer $Name"
}

New-Customer -Name 'Alice Johnson'
try { New-Customer -Name '' } catch { "Blocked. $($_.Exception.Message.Split('.')[0])." }

Output:

Created customer Alice Johnson
Blocked. Cannot validate argument on parameter 'Name'.

[ValidateNotNullOrEmpty()] rejects both $null and an empty string, and the error names the parameter for you.

Frequently Asked Questions

How do I check if a string is null or empty in PowerShell?

Use [string]::IsNullOrEmpty($value). It returns True for $null and an empty string. Use IsNullOrWhiteSpace if spaces should count as empty too.

How do I check if a variable is null in PowerShell?

Use if ($null -eq $value). Keep $null on the left so an array value doesn’t change the result.

How do I check if a variable is empty in PowerShell?

For text, use [string]::IsNullOrWhiteSpace($value). For arrays and hashtables, check $value.Count -eq 0.

How do I set a value to an empty string if it’s null?

In PowerShell 7, use $value ??= ''. In Windows PowerShell 5.1, cast it with [string]$value or use if ($null -eq $value) { $value = '' }.

Does if ($variable) treat 0 as empty?

Yes. 0, $false, an empty string and an empty array are all False. Use $null -eq when 0 is a valid value.

Other guides that deal with missing values: