Use enum types in PowerShell

Viewed 940

I'm kinda new in powershell (expected start of message :)). I wasn't been able to find answer on my question here or somewhere else, so could somebody help me, please?

For example, we want to use some enum declared in .NET libraries. How we use it in .NET? Kind of like:

using System.Data.SqlClient;

public class Test {
   var x = SortOrder.Ascending;
}

If I need to use it in powershell, as I understood I need to write something like:

$x = [System.Data.SqlClient.SortOrder]::Ascending

So, the question is, is it possible in powershell to use something like 'using' as in C# to shorten the syntax to kind of like: $sortOrder.Ascending or [SortOrder]::Ascending?

1 Answers

Option 1

Store the enum type in a variable:

$so = [System.Data.SqlClient.SortOrder]
$so::Ascending

Option 2

Create a custom type accelerator (for the current session only):

[PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Add("so", "System.Data.SqlClient.SortOrder")
[so]::Ascending

Option 3 (PSv5+)

Introduced in PowerShell v5: add a using to your $profile:

using namespace System.Data.SqlClient

# in your script:
[SortOrder]::Ascending

Option 4

Use a string. In most scenarios (when the target type is known, e.g. for method calls, property assignments etc.) it will be recognized and converted automatically.

For example, if you have this type:

using System.Data.SqlClient;

namespace Example
{
    public class MyClient
    {
       public SortOrder SortOrder { get; set; }
    }
}

You can simply do this:

$myClient = New-Object Example.MyClient
$myClient.SortOrder = "Ascending"

Or also for explicitly typed variables:

[System.Data.SqlClient.SortOrder]$sortOrder = "Ascending"

It's case sensitive and even accepts partial input as long as it's unambiguous:

[System.Data.SqlClient.SortOrder]$sortOrder = "asc"
Related