PowerShell
string manipulation
null check
scripting
programming tips

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Use [string]::IsNullOrEmpty($value) to check whether a string is $null or "" in PowerShell. If whitespace-only strings should also count as empty, use [string]::IsNullOrWhiteSpace($value) instead. Both are .NET static methods available in every PowerShell version since 2.0, and they are more reliable than trusting PowerShell's implicit boolean coercion.

IsNullOrEmpty: The Standard Check

[string]::IsNullOrEmpty() returns $true when the input is either $null or a zero-length string. This is the right choice when whitespace characters are considered valid content.

powershell
1$username = ""
2
3if ([string]::IsNullOrEmpty($username)) {
4    Write-Host "Username is required"
5}

This method maps directly to the .NET String.IsNullOrEmpty method, so its behavior is identical to what C# developers expect. It does not consider " " (whitespace) as empty.

powershell
1# Whitespace is NOT empty for IsNullOrEmpty
2[string]::IsNullOrEmpty("   ")   # Returns False
3[string]::IsNullOrEmpty("")      # Returns True
4[string]::IsNullOrEmpty($null)   # Returns True
5[string]::IsNullOrEmpty("hello") # Returns False

IsNullOrWhiteSpace: When Blanks Should Be Rejected

In most input validation scenarios, a string containing only spaces, tabs, or newlines should be treated the same as an empty string. [string]::IsNullOrWhiteSpace() covers all three cases.

powershell
1$configValue = "   "
2
3if ([string]::IsNullOrWhiteSpace($configValue)) {
4    Write-Host "Configuration value is missing or blank"
5}

This is typically the better default for configuration files, user input, and command-line arguments where visually blank input is meaningless.

powershell
1[string]::IsNullOrWhiteSpace($null)    # True
2[string]::IsNullOrWhiteSpace("")       # True
3[string]::IsNullOrWhiteSpace("   ")    # True
4[string]::IsNullOrWhiteSpace("`t`n")   # True  (tab + newline)
5[string]::IsNullOrWhiteSpace("data")   # False

Direct $null Comparison

Sometimes you need to distinguish between a variable that was never assigned ($null) and one that was explicitly set to an empty string. In that case, compare directly.

powershell
1param(
2    [string]$InputPath
3)
4
5if ($null -eq $InputPath) {
6    Write-Host "Parameter was not provided"
7} elseif ($InputPath -eq "") {
8    Write-Host "Parameter was provided but empty"
9} else {
10    Write-Host "Processing: $InputPath"
11}

Always place $null on the left side of the -eq operator. PowerShell's comparison operators behave differently when a collection appears on the left side, and placing $null first avoids that ambiguity.

powershell
1# Correct: $null on the left
2if ($null -eq $value) { ... }
3
4# Risky: if $value is an array, this filters instead of comparing
5if ($value -eq $null) { ... }

Why You Should Avoid -not $value

PowerShell allows boolean coercion with if (-not $value), and it evaluates to $true for both $null and "". But this approach is fragile.

powershell
1# Works for strings, but the intent is unclear
2$name = ""
3if (-not $name) {
4    Write-Host "This triggers for null and empty"
5}

The problem is that -not also evaluates to $true for the integer 0, an empty array, and other falsy values. If the variable type changes during refactoring, this check silently changes meaning.

powershell
1# Dangerous: this also triggers for 0, @(), and $false
2$count = 0
3if (-not $count) {
4    Write-Host "Is this null? Empty? Zero? All of the above."
5}

For string validation, explicit string methods communicate intent and prevent category errors.

Comparison Table

MethodCatches $nullCatches ""Catches " "Type-SafeRecommended For
[string]::IsNullOrEmpty()YesYesNoYesStrict null/empty checks
[string]::IsNullOrWhiteSpace()YesYesYesYesInput validation
$null -eq $valueYesNoNoYesDistinguishing null from empty
-not $valueYesYesNoNoQuick scripts only
$value.Length -eq 0No (throws)YesNoPartialAvoid (null-unsafe)

Parameter Validation Attributes

PowerShell functions support validation attributes that reject bad input at the boundary, before your logic runs. This is often better than scattering null checks throughout the function body.

powershell
1function Set-ProjectName {
2    param(
3        [ValidateNotNullOrEmpty()]
4        [string]$Name
5    )
6
7    Write-Host "Project name set to: $Name"
8}
9
10# These throw a validation error immediately:
11Set-ProjectName -Name ""
12Set-ProjectName -Name $null

For stricter validation that also rejects whitespace:

powershell
1function Set-Description {
2    param(
3        [ValidateScript({ -not [string]::IsNullOrWhiteSpace($_) })]
4        [string]$Text
5    )
6
7    Write-Host "Description: $Text"
8}

Centralizing Checks with a Helper Function

When the same validation pattern repeats across a script, extract it into a helper to keep behavior consistent.

powershell
1function Test-BlankString {
2    param(
3        [AllowNull()]
4        [AllowEmptyString()]
5        [string]$Value
6    )
7
8    return [string]::IsNullOrWhiteSpace($Value)
9}
10
11# Usage
12Test-BlankString $null       # True
13Test-BlankString ""          # True
14Test-BlankString "   "       # True
15Test-BlankString "content"   # False

Note the [AllowNull()] and [AllowEmptyString()] attributes. Without them, PowerShell's parameter binding coerces $null to "" before the function body runs, which would change the behavior.

Practical Example: Config File Validation

Here is a real-world pattern that combines these techniques to validate a configuration hashtable:

powershell
1function Test-Config {
2    param(
3        [hashtable]$Config
4    )
5
6    $required = @("ServerUrl", "ApiKey", "Environment")
7
8    foreach ($key in $required) {
9        if (-not $Config.ContainsKey($key)) {
10            Write-Error "Missing config key: $key"
11            return $false
12        }
13
14        if ([string]::IsNullOrWhiteSpace($Config[$key])) {
15            Write-Error "Config key '$key' is blank"
16            return $false
17        }
18    }
19
20    Write-Host "Configuration is valid"
21    return $true
22}
23
24$settings = @{
25    ServerUrl   = "https://api.example.com"
26    ApiKey      = "sk-abc123"
27    Environment = ""
28}
29
30Test-Config -Config $settings
31# Output: Config key 'Environment' is blank

Common Pitfalls

  • Using -not $value for string validation when the variable might later hold a non-string type. The check silently changes meaning.
  • Choosing IsNullOrEmpty when whitespace-only input should also be rejected. Users who paste spaces into a form field will bypass the check.
  • Placing $value on the left side of -eq $null. If $value is an array, PowerShell filters the array instead of comparing it.
  • Checking $value.Length -eq 0 without first checking for $null. This throws a NullReferenceException equivalent error.
  • Forgetting [AllowNull()] on function parameters. PowerShell coerces $null to "" for [string] parameters by default, which masks true null values.
  • Repeating slightly different validation conditions throughout a script instead of using a shared helper or parameter validation attribute.

Summary

  • [string]::IsNullOrEmpty() is the standard check for null or zero-length strings.
  • [string]::IsNullOrWhiteSpace() is the better default for input validation because it also catches whitespace-only strings.
  • Use direct $null -eq $value comparison only when you must distinguish null from empty.
  • Avoid -not $value for string validation. It works by accident and breaks when the type changes.
  • Use [ValidateNotNullOrEmpty()] on function parameters to catch bad input at the boundary.
  • Centralize repeated checks in a helper function to keep validation consistent across scripts.

Course illustration
Course illustration

All Rights Reserved.