Powershell参数验证没有抛出异常

时间:2014-07-10 11:59:19

标签: powershell parameters

我有像这样的Powershell脚本

    Param(
   [Parameter(Mandatory=$True,Position=1)]
   [string]$variable1,

   [Parameter(Mandatory=$True,Position=2)]
   [string]$variable2,

   [Parameter(Mandatory=$True,Position=3)]
   [int]variable3
   )... something happens then

现在我想在继续使用脚本之前检查如果变量1例如是A,B或C变量2是D,E或F而变量3是1,4,5

是否有可能在输入后立即检查参数?因此,如果variable1错误你必须重做它但如果variable2有错误你只需要重做variable2而不是variable1吗?

2 个答案:

答案 0 :(得分:1)

使用ValidateSet属性指定可接受的值。

来自帮助文档about_Functions_Advanced_Parameters

ValidateSet Attribute
    The ValidateSet attribute specifies a set of valid values for a 
    parameter or variable. Windows PowerShell generates an error if a
    parameter or variable value does not match a value in the set. In
    the following example, the value of the Detail parameter can only
    be "Low," "Average," or "High."

   Param
      (
        [parameter(Mandatory=$true)]
        [ValidateSet("Low", "Average", "High")]
        [String[]]
        $Detail
      ) 

答案 1 :(得分:0)

function testFunc{
    Param(
    [Parameter(Mandatory=$True,Position=1)]
    $variable1,

    [Parameter(Mandatory=$True,Position=2)]
    $variable2,

    [Parameter(Mandatory=$True,Position=3)]
    $variable3)

    $acceptable1 = @("A", "B", "C")
    $acceptable2 = @("D", "E")
    $acceptable3 = @(1, 2, 3)

    while((-Not($acceptable1.Contains($variable1))) -or (-Not($acceptable2.Contains($variable2))) -or (-Not($acceptable3.Contains($variable3)))){
        if (-Not($acceptable1.Contains($variable1))){
            $variable1 = Read-Host "Please re-enter Variable1"
        }
        if (-Not($acceptable2.Contains($variable2))){
            $variable2 = Read-Host "Please re-enter Variable2"
        }
        if (-Not($acceptable3.Contains($variable3))){
            $variable3 = Read-Host "Please re-enter Variable3" 
            if([int]$variable3 -eq [double]$variable3){
                $variable3 = [int] $variable3
            }
        }
    }
}

不是最优雅,但它有效。

我定义了3组可接受的输入,然后根据集合进行检查。它将继续循环,直到每个输入都正确。由于Read-Host接受了字符串,我检查了int cast是否等于double cast,然后将变量设置为int。

这只会提示您按照指定更正错误的输入。