Search code examples
powershellenumspowershell-2.0powershell-4.0powershell-cmdlet

How to pass a custom enum to a function in powershell


When defining a function, how can you reference a custom enum?

Here's what I'm trying:

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

But this gives the error:

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

NB: I'm aware I could use ValidateSet for similar functionality; however that has the disadvantage of only having a name value; as opposed to allowing me to program using friendly names which are then mapped to ints in the background (I could write code for that; but enum seems more appropriate if possible).

I'm using Powershell v4, but ideally I'd like a PowerShell v2 compatible solution as most users are on that version by default.

Update

I've corrected the typo (thanks PetSerAl; well spotted). [JB.InterfaceZones]$zone now changed to [JB.InternetZones]$zone. Now I'm seeing error:

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

Solution

  • The ISE gave this one away to me but your attempted syntax was not completely incorrect. I was able to do this and get it to work.

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

    Again, If you look at the highlighting you will see how I came to that conclusion.

    syntax highlighting