Author Posts

May 18, 2016 at 2:50 am

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~

May 18, 2016 at 9:53 am

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

May 18, 2016 at 11:10 am

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

May 19, 2016 at 4:30 am

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 :

$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


#Use add-type to compile C# code
Add-Type -TypeDefinition $HereString 

[Enum]::GetNames( [testenum] )

#Check displays

May 19, 2016 at 7:43 am

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