我有以下 PowerShell 脚本,我想在其中进行以下更改:
如有任何帮助,我们将不胜感激!
谢谢!
Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All" -NoWelcome
Add-Type -AssemblyName System.Web
$uri = [System.UriBuilder] 'https://graph.microsoft.com'
function Get-GroupMembersId {
[CmdletBinding()]
param([string] $uri)
do {
$response = Invoke-MgGraphRequest GET $uri -Headers @{ ConsistencyLevel = 'eventual' }
$uri = $response.'@odata.nextLink'
if ($null -ne $response.value) {
$response.value.Id
}
}
while ($uri)
}
$tmSku = Get-MgSubscribedSku -All | Where SkuPartNumber -in ('SKU1', 'SKU2', 'SKU3', 'SKU4', 'SKU5')
foreach ($sku in $tmSku)
{
$getMgUserSplat = @{
Filter = "assignedLicenses/any(x: x/skuId eq $($sku.SkuId))"
Select = 'DisplayName', 'Id', 'Mail', 'UserPrincipalName', 'JobTitle'
All = $true
}
$users += Get-MgUser @getMgUserSplat
$userCount = $users | Measure-Object
}
$result = foreach ($user in $users) {
$outObject = [ordered]@{
Id = $user.Id
DisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
Mail = $user.Mail
JobTitle = $user.JobTitle
}
[pscustomobject] $outObject
}
Write-Host "Found " $userCount.Count " licensed users."
$result
创建 2 个哈希表:
$tmSku = Get-MgSubscribedSku -All | Where SkuPartNumber -in ('SKU1', 'SKU2', 'SKU3', 'SKU4', 'SKU5')
# create a hashtable to keep track of users and their license assignments
$users = @{}
$assignedSKUs = @{}
foreach ($sku in $tmSku) {
$getMgUserSplat = @{
Filter = "assignedLicenses/any(x: x/skuId eq $($sku.SkuId))"
Select = 'DisplayName', 'Id', 'Mail', 'UserPrincipalName', 'JobTitle'
All = $true
}
Get-MgUser @getMgUserSplat |ForEach-Objects {
# populate user table
if (-not $users.Contains($_.Id)) {
$users[$_.Id] = $_
}
# populate SKU table
if (-not $assignedSKUs.Contains($_.Id)) {
# use a hashset to store the user IDs associated with a given SKU
$assignedSKUs = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
}
[void]$assignedSKUs[$sku.SkuId].Add($_.Id)
}
}
现在我们已经收集了相关信息,迭代
$users
表中的条目以创建每个输出记录,并根据 $assignedSKUs
表的内容动态添加属性:
$result = @(
foreach ($userID in $users.psbase.Keys) {
$user = $users[$userID]
# create object template with ordered dictionary just like before
$outObject = [ordered]@{
Id = $user.Id
DisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
Mail = $user.Mail
JobTitle = $user.JobTitle
}
# ... but then we also attach and populate all SKU columns to it
foreach ($sku in $tmSku) {
$outObject[$sku.SkuId] = $assignedSKU[$sku.SkuId].Contains($user.Id)
}
# ... and finally create the output object just like before
[pscustomobject]$outObject
}
)
Write-Host "Found $($result.Count) licensed users."
# turn the properties into "columns" in a CSV file
$result |Export-Csv -NoTypeInformation -Path path\to\user_licenses.csv