2015-03-13 133 views
0

定義函數時,如何引用自定義枚舉?如何將自定義枚舉傳遞給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.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

你的函數聲明'$ zone'爲'[JB.InterfaceZones]'不是'[JB.InternetZones]'。 – PetSerAl 2015-03-13 12:17:05

+0

Doh!謝謝 - 雖然仍然有一個錯誤(更新後) – JohnLBevan 2015-03-13 12:27:28

+1

只是這樣調用它:'Get-InternetZoneLogonMode -zone TrustedSites' – 2015-03-13 12:36:13

回答

2

的ISE了這一個遠離我,但你試圖語法不完全不正確。我能夠做到這一點,並將其付諸實施。

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

再次,如果你看看突出顯示,你會看到我如何得出這個結論。

syntax highlighting

+0

啊,不錯 - 謝謝你:) – JohnLBevan 2015-03-13 16:46:44

0

每評論由PetSerAl & CB:

  • 在函數定義

    更正錯字

    • [JB.InterfaceZones]$zone
    • [JB.InternetZones]$zone
  • 更改的功能調用

    • Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
    • Get-InternetZoneLogonMode -zone TrustedSites
相關問題