PowerShell and using .Net enum types

[NOTE: Because this page is the first hit in Google when you search on Powershell + enum, and I landed on this page too often myself, I decided to expand the page with some additional information] 

Scripting is heaven when you can utilize the complete .Net framework. One thing that was not directly clear for me was how to use enum values when calling .Net functions. It happened to be really easy, just cast the string representative of the enum value.

$myString = "/A/B/C//D/E//F/G"

$myParts = $myString.Split("/", [System.StringSplitOptions]"RemoveEmptyEntries")

results in an array of A,B,C,D,E,F,G

UPDATE: it happens to be even easier, you can say:


And you can even binary-or them together:

[System.Text.RegularExpressions.RegexOptions]::Singleline -bor [System.Text.RegularExpressions.RegexOptions]::ExplicitCapture

It is also possible that an enum is defined within an enclosed type, in this case use [<namespace>.<enclosing type>+<nested type>]::EnumValue (thanks Alex)

For example:


It is also possible to create a new real .net enum from PowerShell script. See http://blogs.msdn.com/powershell/archive/2007/01/23/how-to-create-enum-in-powershell.aspx

And in PowerShell 2.0 you can do it even cleaner: http://thepowershellguy.com/blogs/posh/archive/2008/06/02/powershell-v2-ctp2-making-custom-enums-using-add-type.aspx


Published Monday, December 11, 2006 12:37 PM by svdoever
Filed under: ,


No Comments