如何将自定义枚举传递给powershell中的函数
问题描述:
定义函数时,如何引用自定义枚举?如何将自定义枚举传递给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
答
的ISE了这一个远离我,但你试图语法不完全不正确。我能够做到这一点,并将其付诸实施。
Get-InternetZoneLogonMode -Zone ([JB.InternetZones]::TrustedSites)
再次,如果你看看突出显示,你会看到我如何得出这个结论。
+0
啊,不错 - 谢谢你:) – JohnLBevan 2015-03-13 16:46:44
答
每评论由PetSerAl & CB:
- 在函数定义
更正错字
- 从
[JB.InterfaceZones]$zone
- 到
[JB.InternetZones]$zone
- 从
-
更改的功能调用
- 从
Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
- 到
Get-InternetZoneLogonMode -zone TrustedSites
- 从
你的函数声明'$ zone'为'[JB.InterfaceZones]'不是'[JB.InternetZones]'。 – PetSerAl 2015-03-13 12:17:05
Doh!谢谢 - 虽然仍然有一个错误(更新后) – JohnLBevan 2015-03-13 12:27:28
只是这样调用它:'Get-InternetZoneLogonMode -zone TrustedSites' – 2015-03-13 12:36:13