【问题标题】:Powershell Auto-Complete on ValidationSetValidationSet 上的 Powershell 自动完成
【发布时间】:2016-12-20 23:58:15
【问题描述】:

创建验证集很容易。

param(
[Parameter(Mandatory=$true)]
[ValidateSet('Ding','Dong')]
[string]$bellState,

[Parameter(Mandatory=$true)]
[ValidateSet('Dead','Alive')]
[string]$witchesState

)

如果您的 Powershell 版本 >2,它会提供免费的自动完成功能

但是,如果你一开始不传递参数,它就没有那么有用了。

cmdlet Untitled2.ps1 at command pipeline position 1
Supply values for the following parameters:
bellState: Dib
witchesState: Alive
C:\Users\cac\Untitled2.ps1 : Cannot validate argument on parameter 'bellState'. The argument "Dib" does not belong to the set "Ding,Dong" specified by the ValidateSet attribute. Supply an argument that is in the set and then 
try the command again.
+ CategoryInfo          : InvalidData: (:) [Untitled2.ps1],     ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Untitled2.ps1     

这次没有tab补全或线索:(

如果你输入了无效的内容,你会得到一个有用的错误:

"The argument "Dib" does not belong to the set "Ding,Dong""

但是,这个错误是在参数末尾而不是在最初的错误发生时抛出的,并且没有重试的选项。

有没有人找到一种方法来扩展此验证,使其在未传入参数的情况下启动的实例更加用户友好。

【问题讨论】:

  • 我不知道使用 ValidateSet 扩展的方法。我唯一知道的方法是使用Read-Host cmdlet 并自己动手,但我不建议您这样做。你可能应该忍受它。

标签: validation powershell user-interface


【解决方案1】:

虽然它可能不是您想要的,但我认为对脚本的一个简单添加就是将 HelpMessages 添加到您的参数中。这样,用户可以选择获取有关他们将要输入的内容的更多信息。

param(
[Parameter(Mandatory=$true,
    HelpMessage="You need to pick ding or dong silly")]
[ValidateSet('Ding','Dong')]
[string]$bellState,

[Parameter(Mandatory=$true)]
[ValidateSet('Dead','Alive')]
[string]$witchesState

)

所以在不指定参数的情况下调用...

Supply values for the following parameters:
(Type !? for Help.)
bellState: !?
You need to pick ding or dong silly
bellState: 

【讨论】:

  • 正是@Matt 我正要自己添加这个,请参阅:HelpMessage Argument。这不完全是我想要的,但总比让用户失明要好。现在只看动态参数。
【解决方案2】:

如果我删除强制位并在参数块之后添加一些代码,我可以获得我想要的结果。我知道这可能会使管道等的 Cmdlet 变得非常无用,所以我明白为什么它不是默认行为。

我通过使用强制参数执行实际工作的函数并使用单独的辅助函数来获取用户输入来解决这个问题。

让下面的事情做任何你想做的事情并不是那么冗长或棘手。

有一个article here

 if(!($bellState)){
        $title = "Pick a Bell State"
        $message = "You need to pick ding or dong silly"

        $Ding = New-Object System.Management.Automation.Host.ChoiceDescription "Ding", `
            "First Strike."

        $Dong = New-Object System.Management.Automation.Host.ChoiceDescription "Dong", `
            "Second Strike."

        $options = [System.Management.Automation.Host.ChoiceDescription[]]($Ding, $Dong)

        $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

        switch ($result)
            {
                0 { $type = "Ding" ; "First Strike."}
                1 { $type = "Dong" ; "Second Strike."}
            }

 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2015-06-10
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多