#Requires -Version 2.0
[CmdletBinding()]
Param(
[Parameter()] [string] $MyParam = $null
)
if($MyParam -eq $null) {
Write-Host 'works'
} else {
Write-Host 'does not work'
}
Outputs "does not work" => looks like strings are converted from null to empty string implicitly? Why? And how to test if a string is empty or really $null? This should be two different values!
Okay, found the answer @ https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/
Assuming:
And the parameter was not specified (is using default value):
Alternatively, you can specify a special null type:
In which case the
$null -eq $stringParam
will work as expected.Weird!
You will need to use the
AllowNull
attribute if you want to allow$null
for string parameters:And note that you should use $null on the left-hand side of the comparison:
if you want it to work predictably
So it seems a default value of
$null
for parameters of type[string]
defaults to empty string, for whatever reason.Option 1
Option 2
Option 3
Simply do not declare the param's type if you want a $null value to remain:
(None of the other solutions worked for me when declaring the type.)
seeing many equality comparisons with [String]::Empty, you could use the [String]::IsNullOrWhiteSpace or [String]::IsNullOrEmpty static methods, like the following:
which yields: