简体   繁体   English

当null时,powershell强制性参数将引发错误

[英]powershell mandatory parameter throws error when null

I am confused about how to do error handling in the case that a mandatory variable remains null. 我对强制变量保持为null的情况下的错误处理感到困惑。

function parse-com{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True)]
        [string[]]$list
     )
...

In this case if no argument is passed for $list then I am prompted for it, but if I just hit enter (pass a null to $list) then I throw an error. 在这种情况下,如果没有为$ list传递任何参数,那么系统会提示我输入它,但是如果我只是按Enter键(将null传递给$ list),则会抛出错误。 What I would rather do is throw a usage statement and/or exit gracefully. 我宁愿做的是抛出用法声明和/或正常退出。 Example... 例...

PS C:\Users\memyself> parse-com
cmdlet parse-com at command pipeline position 1
Supply values for the following parameters:
list[0]: 
parse-com : Cannot bind argument to parameter 'list' because it is an empty array.
At line:1 char:1
+ parse-com
+ ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [parse-com], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,parse-com

When passing a $null value, that satisfies the Mandatory requirement. 传递$null值时,满足Mandatory要求。 If you want the command then to fail prior to execution then you should use validation as @JeffZeitlin suggests. 如果您希望该命令在执行之前失败,则应按照@JeffZeitlin的建议使用验证。

It sounds like what you need to validate is that the value is not $null nor is it an empty array. 听起来您需要验证的是该值不是$null也不是空数组。 For which you could user [ValidateNotNullOrEmpty()] 您可以为此使用[ValidateNotNullOrEmpty()]

function parse-com{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string[]]$list
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM