powershell, dynamically create a modifiable enum at run time

33 Views Asked by At

I want to dynamically create a modifiable enum at runtime from data stored in a [string[]]

at first I used

$fruits = 'apple','orange'
Add-Type "public enum fruits { $($fruits -join ",`n") }"

but when on the second run the fruits list change I get the add-type : Cannot add type. The type name 'fruits' already exists. error

I then tried

$fruits = 'apple','orange'
[scriptblock]::create("enum fruits {$($fruits -join "`n")}").invoke()

but the script is executed in its own context and the newly created enum is not visible

I then found this way to dot-source a scriptblock

$fruits = 'apple','orange'
$executioncontext.InvokeCommand.InvokeScript($false, [scriptblock]::create("enum fruits {$($fruits -join "`n")}"), $null, $null)

now I can dynamically redefine my enum at will without any error. eg,

$fruits = 'apple','orange','banana'
$executioncontext.InvokeCommand.InvokeScript($false, [scriptblock]::create("enum fruits {$($fruits -join "`n")}"), $null, $null)

this works very well but seems to me a bit complicated. did I miss something? is there a simpler way to dynamically create a modifiable enum in Powershell 5.1?

context

PSVersion                      5.1.19041.4046
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.4046
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
1

There are 1 best solutions below

3
Peyre On BEST ANSWER

oops... the answer was obvious

$fruits = 'apple','orange','peach'
$CreateEnum = [scriptblock]::create("enum fruits {$($fruits -join "`n")}")
. $CreateEnum

or even simpler,

$fruits = 'apple','orange','peach'
. ([scriptblock]::create("enum fruits {$($fruits -join "`n")}"))