PowerShell string default parameter value does not work as expected

D.R. picture D.R. · Apr 7, 2014 · Viewed 52.2k times · Source
#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

D.R. picture D.R. · Apr 7, 2014

Okay, found the answer @ https://www.codykonior.com/2013/10/17/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!