验证参数真的有用吗?

Nic*_*ssu 5 powershell

我正在研究powershell函数及其验证参数.但是我无法理解它们是否真的有用.

我举一个简单的例子.

function get-choice(
[parameter(Mandatory=$true)][String][ValidateSet('Y','N')]$choice
)
{return $choice}

get-choice k
Run Code Online (Sandbox Code Playgroud)

此函数返回此错误:

get-choice : Impossibile convalidare l'argomento sul parametro 'choice'. L'argomento "k" non appartiene al set "Y,N" specificato dall'attributo ValidateSet. Fornire un argomento inclu
so nel set ed eseguire di nuovo il comando.
In riga:6 car:11
+ get-choice <<<<  k
    + CategoryInfo          : InvalidData: (:) [get-choice], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,get-choice
Run Code Online (Sandbox Code Playgroud)

如果我没有指定一组有效的值,我可以在我的代码中检查它们:

function get-choice2(
[parameter(Mandatory=$true)][String]$choice
) {
    if($choice -ne 'y' -and $choice -ne 'n') {
        write-host "you must choose between yes and no"
        return
    }
return $choice
}

get-choice2 k
Run Code Online (Sandbox Code Playgroud)

我得到一个更友好的信息:

you must choose between yes and no
Run Code Online (Sandbox Code Playgroud)

首先,我想知道是否可以使用validateset自定义错误消息.然后我希望有人可以解释为什么我不得不首选方法.提前致谢.

ste*_*tej 6

使用标准验证的一些原因:

  • 陈述性代码; 这if句话更容易阅读
  • 更短(4行代码与1行只有return声明相比)
  • 自定义代码可能有一些错误
  • 稍后在PowerShell的Vx中可能会有一些自定义验证消息(?)(只是做梦)
  • ...

检查PowerShell ValidatePattern的更好的错误消息 - 由@jaykul发布.您将看到如何自定义错误消息.它有点面向开发人员,但值得一读.