如何将自定义枚举传递给PowerShell中的函数

时间:2015-03-13 12:10:38

标签: powershell enums powershell-v2.0 powershell-v4.0 pscmdlet

定义函数时,如何引用自定义枚举?

这是我尝试的内容:

Add-Type -TypeDefinition @"
   namespace JB
   {
       public enum InternetZones
       {
          Computer
          ,LocalIntranet
          ,TrustedSites
          ,Internet
          ,RestrictedSites
       }
   }
"@ -Language CSharpVersion3

function Get-InternetZoneLogonMode
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]   
        [JB.InterfaceZones]$zone
    )
    [string]$regpath = ("HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\{0}" -f [int]$zone)
    $regpath
    #...
    #Get-PropertyValue 
}

Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites

但这会产生错误:

Get-ZoneLogonMode : Unable to find type [JB.InterfaceZones]. Make sure that the assembly that contains this type is loaded.
At line:29 char:1
+ Get-ZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (JB.InterfaceZones:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

注意:我知道我可以使用ValidateSet来实现类似功能;但是它的缺点是只有名称值;而不是允许我使用友好名称编程,然后在后台映射到整数(我可以为此编写代码;但如果可能,枚举似乎更合适)。

我使用的是Powershell v4,但理想情况下我喜欢与PowerShell v2兼容的解决方案,因为大多数用户默认使用该版本。

更新

我已经纠正了错字(感谢PetSerAl;很好看)。 [JB.InterfaceZones]$zone现已更改为[JB.InternetZones]$zone。 现在我看到了错误:

Get-InternetZoneLogonMode : Cannot process argument transformation on parameter 'zone'. Cannot convert value "[JB.InternetZones]::TrustedSites" to type 
"JB.InternetZones". Error: "Unable to match the identifier name [JB.InternetZones]::TrustedSites to a valid enumerator name.  Specify one of the following 
enumerator names and try again: Computer, LocalIntranet, TrustedSites, Internet, RestrictedSites"
At line:80 char:33
+ Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-InternetZoneLogonMode], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-InternetZoneLogonMode

2 个答案:

答案 0 :(得分:2)

ISE向我提供了这个,但您尝试的语法并不完全错误。我能够做到这一点并让它发挥作用。

Get-InternetZoneLogonMode -Zone ([JB.InternetZones]::TrustedSites)

同样,如果你看一下突出显示,你会看到我是如何得出这个结论的。

syntax highlighting

答案 1 :(得分:0)

每篇评论由PetSerAl& CB:

  • 更正了函数定义中的拼写错误

    • 来自[JB.InterfaceZones]$zone
    • [JB.InternetZones]$zone
  • 更改了函数调用

    • 来自Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
    • Get-InternetZoneLogonMode -zone TrustedSites