2

I try to introduce an optional string parameter to my function. Based on this thread should [AllowNull()] do the trick, but PowerShell still populates my parameter with an empty string (using PowerShell version 5.1.14393.206).

The following function illustrates the problem:

function Test-HowToManageOptionsStringParameters() {
    Param(
        [Parameter(Mandatory)]
        [int] $MandatoryParameter,
        [Parameter()]
        [AllowNull()]
        [string] $OptionalStringParameter = $null
    )

    if ($null -eq $OptionalStringParameter) {
        Write-Host -ForegroundColor Green 'This works as expected';
    } else {
        Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL';
    }
}

To makes think even worse is even this code not working (assigning $null to the parameter for testing), I really do not understand why this is not working…

function Test-HowToManageOptionsStringParameters() {
    Param(
        [Parameter(Mandatory)]
        [int] $MandatoryParameter,
        [Parameter()]
        [AllowNull()]
        [string] $OptionalStringParameter = $null
    )

    $OptionalStringParameter = $null;

    if ($null -eq $OptionalStringParameter) {
        Write-Host -ForegroundColor Green 'This works as expected';
    } else {
        Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL';
    }
}
Community
  • 1
  • 1
thuld
  • 680
  • 3
  • 10
  • 29

2 Answers2

2

It seems like is assigning an empty string to your variable if you assign it to $null if its declared as a [string].

You can get arround it by omiting the type [string] on $OptionalStringParameter. Another way would be to check for [string]::IsNullOrEmpty($OptionalStringParameter) within your if statement.

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
0

Change your code to this:

function Test-HowToManageOptionsStringParameters() {
PARAM(
    [Parameter(Mandatory)]
    [int] $MandatoryParameter,
    [Parameter()]
    [AllowNull()]
    [string] $OptionalStringParameter
)

if(-not $OptionalStringParameter) {
    Write-Host -ForegroundColor Green 'This works as expected';
}
else {
    Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL';
}
}

Use either ! or the -not operator to check for null. If think the problem is that you've a typed parameter -> you find an explanation in the comments of this answer.

Hope that helps

Community
  • 1
  • 1
Moerwald
  • 10,448
  • 9
  • 43
  • 83