我尝试向我的函数引入一个可选的字符串参数。 Based on this thread should[AllowNull()]
这样做,但PowerShell仍然使用空字符串填充我的参数(使用PowerShell版本5.1.14393.206)。可选字符串参数(应为NULL)
下面的函数说明了这个问题:
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';
}
}
为了品牌认为更糟糕的是,即使这个代码不工作(分配$null
进行测试参数),我真的不明白为什么这是不工作...
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';
}
}