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

Read carefully before replying! I want to pass an integer to an enumeration type where the integer value is not actually defined in the enumeration. In VB.Net, you can directly distinguish any integer with an integer-based enumeration type using DirectCast. Is there a way to do this natively in PowerShell?

I need to do this in PowerShell to call a method in an Office Interop object ( Access.Application.SysCmd ) that takes an enumeration value as its first argument ( AcSysCmdAction ), but where is the actual value I need to pass (603 for undocumented exports for actions accde) is not included in the definition of renaming a PIA. Converting the built-in PowerShell type causes it to convert a number or string to the corresponding enumeration type, but it will not force an int value that is not in the enumeration. Instead, it throws an invalid conversion exception. Right now I am resorting to a dynamically compiled ScriptControl that calls SysCmd via VBScript, but I would like to save everything in PowerShell, if possible.

+6
source share
2 answers

You can call the Enum class ToObject :

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

Ok, I just figured out the way. An enum object appears in PowerShell that has the "value__" property, 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 
+2
source

Source: https://habr.com/ru/post/950926/


All Articles