You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本优化:将多对多许可证输出转为单用户一行格式

解决PowerShell导出用户许可证横向排列问题

可以通过Group-Object分组用户,再动态生成许可证列的方式实现每个用户一行、多许可证横向排列的需求,具体步骤和代码如下:

核心思路

  1. 先获取用户及对应许可证的基础数据(包含用户信息、许可证友好名称)
  2. 按UserPrincipalName分组,确保同一用户的所有许可证归为一组
  3. 遍历每个用户组,将基础用户信息作为固定列,再把该用户的所有许可证依次转为License1、License2...这类动态列
  4. 导出整理后的数据到Excel/CSV

完整代码示例

1. 获取并预处理用户许可证数据

# 连接Microsoft Online(根据使用的模块调整,这里以Msol为例)
Connect-MsolService

# 定义SkuId到友好名称的映射表(可根据实际环境补充)
$skuFriendlyNames = @{
    "6fd2c87f-b296-42f0-b197-1e91e994b900" = "Microsoft 365 E3"
    "1b0f77d3-9450-460a-a105-e60ec4066575" = "Microsoft 365 E5"
    "70d33638-9c74-4d01-bfd3-562de28bd4ba" = "Office 365 E3"
}

# 获取带许可证的用户,关联许可证友好名称
$rawData = Get-MsolUser -All | Where-Object { $_.Licenses.Count -gt 0 } | ForEach-Object {
    $currentUser = $_
    $_.Licenses | ForEach-Object {
        [PSCustomObject]@{
            DisplayName       = $currentUser.DisplayName
            UserPrincipalName = $currentUser.UserPrincipalName
            LicenseName       = if ($skuFriendlyNames.ContainsKey($_.SkuId)) { $skuFriendlyNames[$_.SkuId] } else { $_.AccountSkuId }
        }
    }
}

2. 分组并转换为横向列格式

# 按用户分组
$groupedUsers = $rawData | Group-Object -Property UserPrincipalName

# 生成最终输出对象
$finalData = $groupedUsers | ForEach-Object {
    # 初始化用户基础信息
    $userOutput = [PSCustomObject]@{
        DisplayName       = $_.Group[0].DisplayName
        UserPrincipalName = $_.Name
    }

    # 动态添加许可证列
    for ($i = 0; $i -lt $_.Group.Count; $i++) {
        $columnName = "License$($i + 1)"
        $userOutput | Add-Member -MemberType NoteProperty -Name $columnName -Value $_.Group[$i].LicenseName
    }

    $userOutput
}

3. 导出到Excel/CSV

# 方法1:用ImportExcel模块导出为Excel(需先安装:Install-Module -Name ImportExcel)
$finalData | Export-Excel -Path "C:\Temp\User_Licenses.xlsx" -AutoSize -BoldTopRow

# 方法2:导出为CSV(无需额外模块,可直接用Excel打开)
$finalData | Export-Csv -Path "C:\Temp\User_Licenses.csv" -NoTypeInformation -Encoding UTF8

注意事项

  • 如果用户的许可证数量不同,PowerShell会自动为许可证较少的用户补充空值,Excel中对应单元格显示为空
  • $skuFriendlyNames映射表建议根据自己租户的实际许可证SkuId补充,确保显示的名称更直观
  • 若使用AzureAD模块而非Msol,只需将Get-MsolUser替换为Get-AzureADUser,Get-MsolAccountSku替换为Get-AzureADSubscribedSku即可适配

内容的提问来源于stack exchange,提问作者Devin Ocheltree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:01:16