在 PowerShell 中访问枚举名称

Accessing enum name in PowerShell

我正在编写 PowerShell 脚本,但在使用枚举类型时遇到了困难。我对 SharePoint Online 执行 REST 调用以获取有关特定组的信息。

$group = Invoke-SPORestMethod -Url "https://tenant.sharepoint.com/sites/site/_api/web/RoleAssignments/GetByPrincipalId(8)?`$expand=RoleDefinitionBindings"
$group.RoleDefinitionBindings.results[0].RoleTypeKind

它 returns 一个 int,RoleTypeKind,它是 [Microsoft.SharePoint.Client.RoleType] 中的一个枚举。我无法访问关联枚举值的名称 属性。我目前正在这样做,但它似乎非常错误:

function getGroupPermissionKind([int]$roleType){
    #https://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.roletype.aspx
    [Enum]::GetValues([Microsoft.SharePoint.Client.RoleType]) | foreach {
        $Name = $_
        $Value = ([Microsoft.SharePoint.Client.RoleType]::$_).value__
        if ($Value -eq $roleType){
            return $Name
        }
    }
}

知道 $group.RoleDefinitionBindings.results[0].RoleTypeKind returns 枚举的正确 int,我怎样才能更直接地访问枚举的名称,而不是使用我想出的看似简陋的实现?

据我所知,您可以只使用转换:

[System.AttributeTargets]4096

这导致

Delegate

如果你需要纯字符串,调用ToString()如下

([System.AttributeTargets]4096).ToString()

不确定我是否理解你的问题。您是否要创建整数值到相应角色名称的反向映射,以便您可以通过其整数值获取名称?这可以通过哈希表来实现,如下所示:

$map = @{}
[enum]::GetValues([Microsoft.SharePoint.Client.RoleType]) | ForEach-Object {
  $map[$_.value__] = $_.ToString()
}

value__ 属性 returns 枚举项的数值,而 ToString() 方法 returns 它的字符串化值,即它的名称。

有了这张地图,您可以这样查找名称:

$map[$group.RoleDefinitionBindings.results[0].RoleTypeKind]