PoshBytes: What The Blank!
In PowerShell, a value that *looks* blank might still contain spaces or tabs. In this PoshBytes short, we explore the difference between IsNullOrEmpty() and IsNullOrWhiteSpace() so your scripts can detect truly blank values.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
Checking if a string is actually empty
Null and empty strings return true
[string]::IsNullOrEmpty($null)
[string]::IsNullOrEmpty('')
[string]::IsNullOrEmpty('hello')
A string with spaces is not considered empty
[string]::IsNullOrEmpty(' ')
Checking if a string is actually blank
[string]::IsNullOrWhiteSpace($null)
[string]::IsNullOrWhiteSpace('')
[string]::IsNullOrWhiteSpace(' ')
[string]::IsNullOrWhiteSpace("`t")
[string]::IsNullOrWhiteSpace('hello')
Real-world example
$users = @(
[pscustomobject]@{Name='Alice'; Department='HR'}
[pscustomobject]@{Name='Bob'; Department=''}
[pscustomobject]@{Name='Charlie'; Department=' '}
[pscustomobject]@{Name='Dana'; Department=$null}
)
$users | ForEach-Object {
if ([string]::IsNullOrWhiteSpace($_.Department)) {
Write-Host "Missing department for $($_.Name)" -ForegroundColor Red
}
else {
Write-Host "$($_.Name) is in $($_.Department)" -ForegroundColor Green
}
}
Wrap Up
• In PowerShell, “blank” can mean $null, empty string ”, or whitespace
• IsNullOrEmpty() only checks for $null and empty strings
• IsNullOrWhiteSpace() also treats spaces, tabs, and other whitespace as blank
• IsNullOrWhiteSpace() is usually better for validating user input or imported data