带有 Graph API 和 PSCustomObject 的 Powershell

问题描述 投票:0回答:1

所以,我只是想找人通过询问来帮助我冲过终点线。

我正在使用 Graph API 从 Microsoft Entra 查询分配给用户的许可证。

到目前为止,我可以查询单个用户,并显示分配的许可证,但我想将信息输出到 PSCustomObject,这就是我迷失的地方。

这段代码查询目录并返回所有用户

$GetUsersUrl = "https://graph.microsoft.com/beta/users"
$Data = Invoke-RestMethod -Uri $GetUsersUrl -Headers $Headers -Method Get 
$Result = ($Data | select-object Value).Value
$Users = $Result | select DisplayName,UserPrincipalName,Id

然后我检查与字符串匹配的 userPrincipalName 并从那里提取分配的许可证

$UPN = ($Users | where {$_.userPrincipalName -like "UPN@domain*"})

$lic = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$($UPN.id)/licenseDetails" -Headers $Headers -Method Get

$skuPartNumber = $((($lic | select-object Value).Value).skuPartNumber)

现在我只想获取那里的输出并将其与 $UPN 变量中的信息一起存储在 PSCustomObject 中。

理想情况下,我想使用 foreach 循环为每个用户执行此操作,但我还没有完全做到这一点(我也愿意接受这方面的帮助和建议)。感谢任何和所有的帮助。

azure powershell microsoft-graph-api microsoft-entra-id
1个回答
0
投票

您缺少的非常重要的事情是处理分页,如果没有这些递归循环机制(下面示例中的

do / while
),您可能最终会丢失信息。假设您想要将
licenseDetails
的输出与
user
的输出合并,您可以这样做:

$uri = 'https://graph.microsoft.com/v1.0/users?$select=displayName, userPrincipalName, id'
$result = do {
    $Data = Invoke-RestMethod -Method Get -Uri $uri -Headers $Headers
    $uri = $Data.'@odata.nextLink'

    foreach ($user in $Data.value) {

        $licenseUri = 'https://graph.microsoft.com/v1.0/users/{0}/licenseDetails' -f $user.id
        $allSkuPartNumbers = do {
            $lic = Invoke-RestMethod -Method Get -Uri $uri -Headers $Headers
            $licenseUri = $lic.'@odata.nextLink'
            if ($lic) {
                $lic.value.skuPartNumber
            }
        }
        while ($licenseUri)

        [pscustomobject]@{
            displayName       = $user.displayName
            userPrincipalName = $user.userPrincipalName
            id                = $user.id
            # `$allSkuPartNumbers` will likely be an array,
            # might need `-join` here if exporting to CSV
            skuPartNumber     = $allSkuPartNumbers
        }
    }
}
while ($uri)

# do stuff with `$result`..
$result
© www.soinside.com 2019 - 2024. All rights reserved.