5

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
  • The term you are looking for is Type Accelerator (this is what it's called). If you google for Powershell Type Accelerator you'll find a lot of information (including that the using statement is introduced in PSv5) Commented Dec 18, 2018 at 9:31

1 Answer 1

9
+300

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"
Sign up to request clarification or add additional context in comments.

2 Comments

And because Jeffrey Snover is flawed, you can get away with "a". You need to give it just enough letters, so it's not ambiguous. :)
@Palansen You're right. I rarely use that though and it's horrible to read (except for the "asc" version maybe)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.