Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Joshua Honig Avatar asked Aug 02 '13 18:08

Joshua Honig


2 Answers

You could call the Enum class's ToObject method:

$day = [Enum]::ToObject([DayOfWeek], 90) 
like image 65
Mike Zboray Avatar answered Nov 08 '22 23:11

Mike Zboray


Well, I just figured out a way. In PowerShell, it appears enum objects have a property called "value__" which can be directly set to any value!

#Create a variable with the desired enum type
$ops = [System.Text.RegularExpressions.RegexOptions]0
#Directly set the value__ property
$ops.value__ = 3450432
like image 30
Joshua Honig Avatar answered Nov 09 '22 00:11

Joshua Honig