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

将Azure AD用户许可检查PowerShell脚本适配VS Code

适配VS Code的Azure AD用户许可筛选脚本(基于Microsoft Graph)

问题根源

AzureAD和MSOnline模块已被官方弃用,VS Code的PowerShell环境默认不再优先支持这类旧模块,推荐使用Microsoft Graph PowerShell模块作为替代——这是当前访问Azure AD数据的标准方式。

解决方案步骤

1. 安装依赖模块

先安装必要的PowerShell模块(需管理员权限):

# 安装Microsoft Graph核心模块
Install-Module Microsoft.Graph -Force -AllowClobber
# 安装Excel导出模块(可选,用CSV导出可跳过)
Install-Module ImportExcel -Force -AllowClobber

2. 完整适配脚本

以下脚本实现连接Microsoft Graph、筛选活跃用户、检查指定许可状态并支持导出Excel:

# 连接Microsoft Graph,请求必要权限
Connect-MgGraph -Scopes "User.Read.All", "Organization.Read.All", "Directory.Read.All"

# 定义需检查的服务计划(ID根据租户许可可能略有调整)
$requiredServices = @(
    @{Name = "Exchange"; ServicePlanId = "43de0ff5-c92c-492b-9116-175376d08c38"}, # EXCHANGE_S_ENTERPRISE
    @{Name = "Teams"; ServicePlanId = "113feb6c-3fe4-4440-bddc-54d774bf0318"},   # TEAMS1
    @{Name = "SharePoint"; ServicePlanId = "5dbe027f-2339-4123-9542-606e4d348a72"}, # SHAREPOINTENTERPRISE
    @{Name = "OneDrive"; ServicePlanId = "e95bec33-7c88-4a70-8e19-b10bd9d0c014"}    # ONEDRIVE_BUSINESS
)

# 获取所有启用的活跃用户
$activeUsers = Get-MgUser -Filter "AccountEnabled eq true" -All $true -Property Id, DisplayName, UserPrincipalName, AssignedLicenses

# 初始化结果数组
$results = @()

# 遍历用户检查许可状态
foreach ($user in $activeUsers) {
    $userResult = [PSCustomObject]@{
        DisplayName = $user.DisplayName
        UserPrincipalName = $user.UserPrincipalName
        MissingServices = @()
    }

    # 逐个检查必需服务是否已分配
    foreach ($service in $requiredServices) {
        $hasService = $user.AssignedLicenses.ServicePlanIds -contains $service.ServicePlanId
        if (-not $hasService) {
            $userResult.MissingServices += $service.Name
        }
    }

    # 转换缺失服务为逗号分隔字符串
    $userResult.MissingServices = $userResult.MissingServices -join ", "

    $results += $userResult
}

# 筛选出至少缺失一项服务的用户
$filteredResults = $results | Where-Object { $_.MissingServices -ne "" }

# 控制台显示结果
$filteredResults | Format-Table DisplayName, UserPrincipalName, MissingServices -AutoSize

# 导出到Excel(替换为CSV可改用下方注释的命令)
$exportPath = ".\MissingUserLicenses.xlsx"
$filteredResults | Export-Excel -Path $exportPath -AutoSize -BoldTopRow
# $filteredResults | Export-Csv -Path ".\MissingLicenses.csv" -NoTypeInformation -Encoding UTF8
Write-Host "结果已导出至: $exportPath"

# 断开Graph连接
Disconnect-MgGraph

3. 关键说明

  • 服务计划ID验证:若租户使用不同版本的Office 365许可,服务计划ID可能有差异。可通过Get-MgSubscribedSku | Select-Object SkuPartNumber, ServicePlans查看租户所有可用服务计划,替换脚本中对应ID。
  • 权限说明:连接时请求的权限仅用于读取用户和许可数据,无需额外高权限。
  • 导出格式替代:不想安装ImportExcel模块时,可改用CSV导出,脚本中已给出注释命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:25:14