可选字符串参数(应为NULL)

时间:2016-11-18 11:38:48

标签: powershell powershell-v5.0

我尝试在我的函数中引入一个可选的字符串参数。 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';
    }
}

2 个答案:

答案 0 :(得分:2)

似乎为您的变量分配一个空字符串,如果您将其分配给$null ,如果将其声明为[string]

您可以通过省略 [string]上的$OptionalStringParameter类型来获取它。另一种方法是在if语句中检查[string]::IsNullOrEmpty($OptionalStringParameter)

答案 1 :(得分:0)

将您的代码更改为:

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

使用!-not运算符检查是否为null。如果认为问题在于你是类型的参数 - >你在answer的评论中找到了解释。

希望有所帮助

相关问题