【问题标题】:Optional String Parameter (should be NULL) [duplicate]可选字符串参数(应为 NULL)[重复]
【发布时间】: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';
    }
}

【问题讨论】:

    标签: powershell powershell-5.0


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      将您的代码更改为:

      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 运算符来检查空值。如果认为问题在于您有一个 typed 参数 -> 您可以在 answer 的 cmets 中找到解释。

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-10
        • 1970-01-01
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多