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

How to pass a custom enum to a function in powershell

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

这是我正在尝试的:

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

根据 PetSerAl 和 CB 的评论:

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

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

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

ISE 把这个交给了我,但您尝试的语法并非完全不正确。我能够做到这一点并让它发挥作用。

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

同样,如果您查看突出显示部分,您就会明白我是如何得出这个结论的。