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.
You could call the Enum
class's ToObject
method:
$day = [Enum]::ToObject([DayOfWeek], 90)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With