2016-07-25 108 views
1

我正在使用PowerShell腳本,我一直在使用枚舉類型時遇到困難。我對SharePoint Online執行REST調用以獲取有關特定組的信息。在PowerShell中訪問枚舉名稱

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

它返回一個int,RoleTypeKind,即在[Microsoft.SharePoint.Client.RoleType]一個枚舉。我無法訪問assciated枚舉值的名稱屬性。目前,我正在做這樣的,但它似乎可怕的錯誤:

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返回枚舉的正確INT,我怎麼能更直接地訪問枚舉的名字而不是看似janky實施我想到了?

回答

3

據我所知,你可以用鑄造:

[System.AttributeTargets]4096 

這導致

Delegate 

如果你需要純字符串,請致電ToString()爲未如下

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

當然,如果我理解你的問題。你想創建一個反向映射的整數值到各自的角色名稱,所以你可以通過它們的整數值獲取名稱?可以用一個哈希表來實現,如下所示:

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

value__的屬性返回一個枚舉項的數字值,而ToString()方法返回其字符串化值,即它的名字。

有了該地圖,你可以看看這名字是這樣的:

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

我不希望做一個反向查找,但我覺得我的實現是可怕的。必須有一種原生的方式來做到這一點,我並沒有把握。 –

+0

呃...我剛剛貼了一張?當然,如果你已經有一個'RoleType'對象而不是數字值,你應該可以通過調用它的'ToString()'方法來獲得名字,如[這個答案]中所建議的(http://stackoverflow.com /一個/1630171分之38568919)。 –