MSGraph查询无法返回组信息:PowerShell脚本获取用户组数据异常
问题原因与解决方案
核心问题
Get-MgUserTransitiveMemberOf 返回的是DirectoryObject类型集合,这是一个通用基类,本身并不包含SecurityEnabled、DisplayName这类安全组特有的属性。即使实际对象是安全组,直接访问这些属性会因为类型不匹配导致过滤条件失效,因此你的Where-Object无法筛选到任何结果。当你移除过滤条件后看到的Microsoft.Graph.PowerShell.Models.MicrosoftGraphDirectoryObject,就是这个基类的实例。
修复方案
有两种可靠的修复方式:
方式一:API层面提前过滤+指定属性
在调用Get-MgUserTransitiveMemberOf时,用-Filter在API端先筛选安全组,同时指定需要的属性,减少本地处理的数据量,也能让PowerShell正确映射属性:
$groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -Property DisplayName,SecurityEnabled -Filter "securityEnabled eq true" -All | Where-Object { $_.DisplayName -like 'bg*' } | Select-Object -ExpandProperty DisplayName
方式二:强制转换对象类型
如果需要保留更多组属性,可以先判断对象类型,再强制转换为MicrosoftGraphGroup类型,就能正常访问组专属属性:
$groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -All | ForEach-Object { if ($_.ODataType -eq '#microsoft.graph.group') { $_ -as [Microsoft.Graph.PowerShell.Models.MicrosoftGraphGroup] } } | Where-Object { $_.SecurityEnabled -eq $true -and $_.DisplayName -like 'bg*' } | Select-Object -ExpandProperty DisplayName
修改后的完整脚本
# Retrieve all users with licenses $licensedUsers = Get-MgUser -Property ID, DisplayName, UserPrincipalName, AssignedLicenses -ConsistencyLevel eventual -All | Where-Object { $_.AssignedLicenses.Count -gt 0 } # Initialize an array to store results $results = @() # Loop through each licensed user foreach ($user in $licensedUsers) { # Get assigned license SKUs $licenseTypes = $user.AssignedLicenses | ForEach-Object { $_.SkuId } # 修复后的组获取逻辑 $groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -Property DisplayName,SecurityEnabled -Filter "securityEnabled eq true" -All | Where-Object { $_.DisplayName -like 'bg*' } | Select-Object -ExpandProperty DisplayName # Store the data in results $results += [PSCustomObject]@{ UserID = $user.Id DisplayName = $user.DisplayName UserPrincipal = $user.UserPrincipalName LicenseTypes = $licenseTypes -join ", " SecurityGroups = $groups -join ", " } } # Output the results in table format $results | Format-Table -AutoSize # Export to CSV # $results | Export-Csv -Path "LicensedUsersWithSecurityGroups.csv" -NoTypeInformation -Encoding UTF8
内容的提问来源于stack exchange,提问作者bigmojo
相关产品推荐
相关产品推荐

