在 PowerShell 中使用枚举类型

Use enum types in PowerShell

我是 powershell 的新手(消息的预期开头 :))。 我无法在这里或其他地方找到我的问题的答案,所以有人可以帮助我吗?

例如,我们想使用一些在 .NET 库中声明的枚举。我们如何在 .NET 中使用它?有点像:

using System.Data.SqlClient;

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

如果我需要在 powershell 中使用它,据我所知,我需要编写如下内容:

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

所以,问题是,在 powershell 中是否可以像在 C# 中那样使用 'using' 之类的东西来将语法缩短为:$sortOrder.Ascending[SortOrder]::Ascending

选项 1

将枚举类型存储在变量中:

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

选项 2

创建自定义 type accelerator(仅针对当前会话):

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

选项 3 (PSv5+)

在 PowerShell v5 中引入:将 using 添加到您的 $profile:

using namespace System.Data.SqlClient

# in your script:
[SortOrder]::Ascending

选项 4

使用字符串。在大多数情况下(当目标类型已知时,例如方法调用、属性 赋值等)它将被自动识别和转换。

例如,如果您有这种类型:

using System.Data.SqlClient;

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

您可以简单地这样做:

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

或者对于显式类型变量:

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

它区分大小写,甚至可以接受部分输入,只要它是明确的:

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