Search code examples
powershellcastingenumscom-interop

How can I coerce an integer to an enum type in PowerShell?


Read carefully before you answer! I want to cast an integer to an enum type where the integer value is not actually defined in the enum. In VB.Net, it is possible to directly cast any integer to an integer-based enum type using DirectCast. Is there some way to accomplish this natively in PowerShell?

I need to do this in PowerShell in order to call a method on an Office Interop object (Access.Application.SysCmd) which takes an enumeration value as its first argument (AcSysCmdAction), but where the actual value I need to pass (603 for the undocumented export to accde action) is not included in the PIA enum definition. PowerShell's built-in type conversion cause it to convert either a number or a string the applicable enumeration type, but it will not coerce an int value that is not in the enum. Instead it throws an invalid conversion exception. Right now I'm resorting to a dynamically compiled ScriptControl which calls SysCmd via VBScript, but I'd like to keep everything in PowerShell if possible.


Solution

  • You could call the Enum class's ToObject method:

    $day = [Enum]::ToObject([DayOfWeek], 90)