PowerShell string default parameter value does not work as expected PowerShell string default parameter value does not work as expected powershell powershell

PowerShell string default parameter value does not work as expected


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 workif ($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!


You will need to use the AllowNull attribute if you want to allow $null for string parameters:

[CmdletBinding()]Param (    [Parameter()]     [AllowNull()]    [string] $MyParam)

And note that you should use $null on the left-hand side of the comparison:

if ($null -eq $MyParam)

if you want it to work predictably


seeing many equality comparisons with [String]::Empty, you could use the [String]::IsNullOrWhiteSpace or [String]::IsNullOrEmpty static methods, like the following:

param(    [string]$parameter = $null)# we know this is false($null -eq $parameter)[String]::IsNullOrWhiteSpace($parameter)[String]::IsNullOrEmpty($parameter)('' -eq $parameter)("" -eq $parameter)

which yields:

PS C:\...> .\foo.ps1FalseTrueTrueTrueTrue