D.R. D.R. - 3 months ago 19
PowerShell Question

PowerShell string default parameter value does not work as expected

#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!

Answer

Okay, found the answer @ http://www.zeninteractions.com/checking-for-null-in-powershell/

Assuming:

Param(
  [string] $stringParam = $null
)

And the parameter was not specified (is using default value):

# will NOT work
if ($null -eq $stringParam)
{
}

# WILL work:
if ($stringParam -eq "" -and $stringParam -eq [String]::Empty)
{
}

Alternatively, you can specify a special null type:

Param(
  [string] $stringParam = [System.Management.Automation.Language.NullString]::Value
)

In which case the $null -eq $stringParam will work as expected.

Weird!