在PowerShell中使用Enum类似的开关参数

我以这种方式在我的PowerShell脚本中使用开关参数。

param( [switch] $Word, [switch] $Excel, [switch] $powerpoint, [switch] $v2007, [switch] $v2010, [switch] $x86, [switch] $x64, ) 

我试图弄清楚任何一个整洁的方式,让它更多的枚举风格。 正如任何人可能猜到的,我希望用户在word,excel和powerpoint之间进行select。 在x2007和v2010之间。

有没有一个简洁的方式来获得input参数枚举风格?

我是PowerShell的新手。 所以,如果这听起来像我不知道明显的东西,那么请指向我的一些链接,我可以阅读有关它。

我将使用ValidateSet参数属性。

来自: about_Functions_Advanced_Parameters

ValidateSet属性为参数或variables指定一组有效值。 如果参数或variables值与集中的值不匹配,则Windows PowerShell会生成错误。

function示例:

 function test-value { param( [Parameter(Position=0)] [ValidateSet('word','excel','powerpoint')] [System.String]$Application, [Parameter(Position=1)] [ValidateSet('v2007','v2010')] [System.String]$Version ) write-host "Application: $Application" write-host "Version: $Version" } PS > test-value -application foo 

输出:

test-value : Cannot validate argument on parameter 'Application'. The argument "foo" does not belong to the set "word,excel,powerpoint" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.

PowerShell团队的这篇博客文章定义了如何在PowerShell 1.0中执行此操作。 在PowerShell 2.0中,您可以使用Add-Type,如下所示:

 C:\PS> Add-Type -TypeDefinition @' >> public enum MyEnum { >> A, >> B, >> C, >> D >> } >> '@ >> 

更新:以下是如何使用枚举:

 C:\PS> function foo([MyEnum]$enum) { $enum } C:\PS> foo ([MyEnum]::A) A 

您需要围绕参数的括号将参数parsing为Type。 这是必需的,因为参数或多或less像string一样处理。 知道这一点,你也可以通过枚举以简单的stringforms传递给他们,PowerShell将会明白:

 C:\PS> foo A A C:\PS> $arg = "B" C:\PS> foo $arg B C:\PS> foo F error* 

错误 – F不是枚举值之一 – 有效值包括A,B,C,D *

您可以使用ValidateSet属性:

 function My-Func { param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [ValidateSet('Word', 'Excel', 'PowerPoint', 'v2007', 'v2010', 'x86', 'x64')] [String]$MyParam ) Write-Host "Performing action for $MyParam" } My-Func -MyParam 'Word' My-Func -MyParam 'v2007' My-Func -MyParam 'SomeVal' 

输出:

 Performing action for Word Performing action for v2007 My-Func : Cannot validate argument on parameter 'MyParam'. The argument "SomeVal" does not belong to the set "Word,Excel,PowerPoint,v2007,v2010,x86,x64" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. At C:\Users\George\Documents\PowerShell V2\ValidateSetTest.ps1:15 char:17 + My-Func -MyParam <<<< 'SomeVal' + CategoryInfo : InvalidData: (:) [My-Func], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,My-Func