Search code examples
powershellenumsadd-type

Add-Type enum with an external list


I use PS 4.0, I have a script with an enum for functions parameter.

Add-Type -TypeDefinition @"
public enum AppEnum
{
    MyFirstItem,
    MySecondItem
}
"@

I use it like this :

Function MyFunction
{
    Param
    (
        [AppEnum]$App
    )
    Return $App
}

But my list for my enum is the same than in my XML file, and this can be modified.

I retrieve my list like this :

($xcf.Apps.W2008.LAN | Get-Member -MemberType Properties).Name | ?{$_ -ne "Repository"}

I'd like to use this dynamic list extracted from my XML file as list for my enum in "Add-Type" but I don't find how and I don't know if it's possible. Do you have any idea how to do that ?


Solution

  • # Get list from your XML file here
    $myEnumList = @("MyFirstItem", "MySecondItem")
    
    $source = "public enum AppEnum { " + ($myEnumList | %{ $_ + "," }) + " }"
    
    Add-Type -TypeDefinition $source
    
    # Let's check value is known
    [AppEnum]::MyFirstItem