【问题标题】:How to validate PowerShell Function Parameters allowing empty strings?如何验证允许空字符串的 PowerShell 函数参数?
【发布时间】:2019-09-17 13:07:03
【问题描述】:

请试试这个:

function f1
{
    param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    [string]
    $Text
    )
    $text
}

function f2
{
    param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    #[string]
    $Text
    )
    $text
}

function f3
{
    param(
    [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
    [string]
    $Text
    )
    $text
}

f1 ''
f2 ''
f3 ''

这里 f1 抛出一个错误。现在试试

f2 $null 
f3 $null    

这次只有 f2 抛出错误。我想要的是一个函数f,所以

f '' # is accepted
f $null # returns an error

【问题讨论】:

  • 对不起,我不明白,你的函数'f2'可以按你的意愿工作。 f2 '' 被接受并且 f2 $null 产生一个错误。
  • @JPB 我认为问题出在数据类型上。

标签: powershell parameters


【解决方案1】:

强制属性阻止空值和空值,并提示您输入值。 要允许空值(包括 null),请添加 AllowEmptyString 参数属性:

function f1
{
    param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    [AllowEmptyString()]
    [string]$Text
    )
    $text
}

【讨论】:

  • 你的版本比 Roman Kuzmin 的版本好,它拒绝像 f1 @(1, 2) 这样的非字符串。 f1 $null 被接受的事实似乎是最轻微的问题。顺便说一句,这与 f3 几乎相同。
  • 尝试将 AllowEmptyString 替换为 ValidateNotNull。它允许空字符串但不允许空值。
  • 不,ValidateNotNull() 对 f1 '' 失败。
【解决方案2】:

这是符合要求的解决方案,但需要注意。

function f1
{
    param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    $Text
    )
    Write-Host 'Working'
    $text
}

f1 ''
f1 $null

输出:

Working
f1 : Cannot bind argument to parameter 'Text' because it is null.

警告

为了满足要求,我们必须省略[string] 的显式类型声明。问题是 PowerShell 倾向于在指定 [string] 类型的任何地方将空值转换为空字符串。因此,如果我们使用类型声明,那么 null 值实际上永远不会出现在函数中。

附:这是提交的相关问题: It isn't possible to pass null as null into a .NET method that has a parameter of type String

【讨论】:

  • 我刚刚意识到这正是function f2。所以,这不是一个真正的答案,也许:)
  • +1 我从一开始就是这么说的;o) 但是你给出解释,你就是那个人。
【解决方案3】:

为了完整起见,如果您希望根据字符串类型验证您的输入,您可以在参数声明之后进行:

function f1
{
    param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    $Text
    )
    if (!($text -eq '') -and !($text -as [string])) {write-host "wrong type"; return }
    $text
}

这个函数的行为如下:

  • 当输入为$null 时抛出“无法绑定参数..”异常
  • 当输入为空字符串时通过
  • 当输入不是字符串时退出并显示消息错误类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多