Create Enum from Array

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~

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

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

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

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!!!

No worries !