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';
}
}