Alex
Alex

Reputation: 633

Inconsistent behavior in powershell with null parameters

I need to write a function in powershell that tells apart a 'parameter not being passed' from one passed with string empty (or any other string)

I wrote it like this:

function Set-X {
    param(
    [AllowNull()][string]$MyParam = [System.Management.Automation.Language.NullString]::Value
    )

    if ($null -ne $MyParam) { write-host 'oops' }
    else { write-host 'ok' }
}

If I call Set-X without parameters from ISE, it works as I expect and prints 'ok'.

But if I do that from the normal console, it prints 'oops'.

What is going on? What is the proper way to do it?

Upvotes: 0

Views: 156

Answers (2)

Alex
Alex

Reputation: 633

As Mathias and BenH have written, the culprit is casting $null to the [string] type, which results in an empty string:

 [string]$null -eq '' #This is True

But for the sample code in Mathias answer to work correctly we also have to replace

[System.Management.Automation.Language.NullString]::Value

with $null

function Set-X {
    param(
    [AllowNull()]$MyParam = $null
    )

    if ($null -ne $MyParam) { write-host 'oops' }
    else { write-host 'ok' }
}

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174455

Allowing the user to pass in a parameter argument value of $null does not change the fact that powershell will attempt to convert it to a [string].

Converting a $null value in powershell to a string results in an empty string:

$str = [string]$null
$null -eq $str # False
'' -eq $str    # True

(same goes for $null -as [string] and "$null")

Remove the type constraint on the MyParam parameter if you not only want to allow $null but also accept $null as a parameter value:

function Set-X {
    param(
    [AllowNull()]$MyParam = [System.Management.Automation.Language.NullString]::Value
    )

    if ($null -ne $MyParam) { write-host 'oops' }
    else { write-host 'ok' }
}

Upvotes: 2

Related Questions