【发布时间】:2016-11-18 11:38:48
【问题描述】:
我尝试在我的函数中引入一个可选的字符串参数。 Based on this thread should [AllowNull()] 可以解决问题,但 PowerShell 仍然使用空字符串填充我的参数(使用 PowerShell 版本 5.1.14393.206)。
下面的函数说明了这个问题:
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';
}
}
【问题讨论】: