Create Enum from Array

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Graham Beer Graham Beer 6 months, 3 weeks ago.

  • Author
    Posts
  • #39226
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    Hello everybody!

    Is it possible to create [enum] from array variable in powershell 5? I intend to use it as semi-dynamic validate set for parameter. I've been doing this with dynamic parameters for a while but this looks much, much cleaner and easier. If it's possible at all.

    Best regards~

  • #39241
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Are you looking to create a list of named constants from an array ?

  • #39244
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    Yes, to create enumeration type with enum keyword out of array stored in variable. Something like enum Constant {$array} except this, obviously, doesn't work.
    Thanks for help.

    Best regards

  • #39263
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Hi Milos,

    By creating a here-string with snippet of C# code you can create an ENUM from an array. Here is the code i've tested with :

    #Array
    $servers = @("server1", "Server2", "Server3")
    
    #Create a Here-string with C# code to create a Enum
    $HereString = 
    @"
       // very simple enum type
       public enum TestEnum
       {
          `n$(foreach ($server in $servers){"`t$server`,"})`n
       }
    "@
    
    #Here-string looks like so
    // very simple enum type
       public enum TestEnum
       {
          
    	server1,
    	Server2,
    	Server3,
    
       } 
    
    #Use add-type to compile C# code
    Add-Type -TypeDefinition $HereString 
    
    #Check
    [Enum]::GetNames( [testenum] )
    
    #Check displays
    server1
    Server2
    Server3
    
  • #39267
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    Thanks Graham, great idea to leverage here-string like that.
    It works with enum keyword and native powershell code wrapped in here-string with invoke-expression cmdlet too.
    Now I can cast function parameter to dynamically created ENUM and get intellisense and validation set without dynamic parameter code.

    Thanks again!!!

  • #39273
    Profile photo of Graham Beer
    Graham Beer
    Participant

    No worries !

You must be logged in to reply to this topic.