适用于 PowerShell 5.1 及以上版本,需安装 Microsoft.Graph 模块
Microsoft Graph 是 Microsoft 365 平台的统一 API 网关——它整合了 Azure AD(现称 Entra ID)、Exchange Online、SharePoint、Teams、OneDrive 等所有 Microsoft 365 服务的数据和操作。通过 PowerShell 的 Microsoft.Graph 模块,运维人员可以用脚本化管理用户、组、许可证、设备策略等,替代传统的多个独立模块。
本文将讲解 Microsoft Graph PowerShell 的连接、用户管理、组操作和常用自动化场景。
连接与认证 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Install-Module -Name Microsoft.Graph -Scope CurrentUser -Force Connect-MgGraph -Scopes "User.Read.All" , "Group.Read.All" , "Directory.Read.All" Get-MgContext | Select-Object Account, Tenant, Scopes | Format-List $clientId = "your-app-client-id" $tenantId = "your-tenant-id" $certThumbprint = "ABC123DEF456" Connect-MgGraph -ClientId $clientId -TenantId $tenantId ` -CertificateThumbprint $certThumbprint Disconnect-MgGraph
执行结果示例:
1 2 3 4 5 Account : admin @contoso.com Tenant : contoso.onmicrosoft.com Scopes : {User .Read .All , Group .Read .All , Directory.Read .All } Welcome To Microsoft Graph!
用户管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 Get-MgUser -All -ConsistencyLevel eventual | Select-Object DisplayName, UserPrincipalName, Mail, Department, JobTitle | Format-Table -AutoSize $user = Get-MgUser -Filter "displayName eq 'John Doe'" -ConsistencyLevel eventual$user | Select-Object Id, DisplayName, UserPrincipalName, Department$newUser = @ { AccountEnabled = $true DisplayName = "张伟" MailNickname = "wei.zhang" UserPrincipalName = "wei.zhang@contoso.com" Department = "IT" JobTitle = "DevOps 工程师" PasswordProfile = @ { ForceChangePasswordNextSignIn = $true Password = "TempP@ssw0rd123!" } } New-MgUser -BodyParameter $newUser Write-Host "用户已创建:wei.zhang@contoso.com" -ForegroundColor GreenUpdate-MgUser -UserId "wei.zhang@contoso.com" -Department "DevOps" Update-MgUser -UserId "wei.zhang@contoso.com" -AccountEnabled :$false Get-MgUserMemberOf -UserId "john.doe@contoso.com" | ForEach-Object { $group = Get-MgGroup -GroupId $_ .Id [PSCustomObject ]@ { GroupName = $group .DisplayName GroupType = $group .GroupTypes -join ',' } } | Format-Table -AutoSize
执行结果示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 DisplayName UserPrincipalName Department JobTitle ----------- ----------------- ---------- --------John Doe john.doe@contoso.com Engineering Senior DevJane Smith jane.smith@contoso.com HR HR ManagerId : 12345678 -abcd-... DisplayName : John DoeUserPrincipalName : john.doe@contoso.com 用户已创建:wei.zhang@contoso.com GroupName GroupType --------- --------- All Users {} IT-Admins {} Developers {DynamicMembership}
组管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Get-MgGroup -All | Select-Object DisplayName, Description, @ {N='类型' ; E={if ($_ .GroupTypes -contains 'Unified' ) { 'Microsoft 365' } else { 'Security' }}}, @ {N='成员数' ; E={$_ .Members.Count}} | Sort-Object DisplayName | Format-Table -AutoSize New-MgGroup -DisplayName "Cloud-Admins" ` -Description "云平台管理员组" ` -MailEnabled :$false ` -SecurityEnabled :$true $userId = (Get-MgUser -Filter "displayName eq 'John Doe'" ).Id$groupId = (Get-MgGroup -Filter "displayName eq 'Cloud-Admins'" ).IdNew-MgGroupMember -GroupId $groupId -DirectoryObjectId $userId Write-Host "已将 John Doe 添加到 Cloud-Admins 组" -ForegroundColor GreenGet-MgGroupMember -GroupId $groupId | ForEach-Object { Get-MgUser -UserId $_ .Id | Select-Object DisplayName, UserPrincipalName } | Format-Table -AutoSize $dynamicGroup = @ { DisplayName = "All-Engineering" Description = "工程部门所有成员" GroupTypes = @ ("DynamicMembership" ) MailEnabled = $false SecurityEnabled = $true MembershipRule = 'user.department -eq "Engineering"' MembershipRuleProcessingState = "On" } New-MgGroup -BodyParameter $dynamicGroup
执行结果示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 DisplayName 类型 成员数----------- ---- ------ All Users Security 245 IT-Admins Security 12 Developers Microsoft 365 35 Cloud-Admins Security 3 已将 John Doe 添加到 Cloud-Admins 组 DisplayName UserPrincipalName----------- ----------------- John Doe john.doe@contoso.com Jane Smith jane.smith@contoso.com
许可证管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Get-MgSubscribedSku | Select-Object SkuPartNumber, @ {N='已用' ; E={$_ .PrepaidUnits.Enabled - $_ .Consumed}}, @ {N='总量' ; E={$_ .PrepaidUnits.Enabled}}, @ {N='已消耗' ; E={$_ .Consumed}} | Format-Table -AutoSize $license = Get-MgSubscribedSku | Where-Object SkuPartNumber -eq 'ENTERPRISEPACK' Set-MgUserLicense -UserId "wei.zhang@contoso.com" ` -AddLicenses @ { SkuId = $license .SkuId } ` -RemoveLicenses @ () Write-Host "已分配 Office 365 E3 许可证" -ForegroundColor Green$users = Get-MgUser -Filter "department eq 'Engineering'" -ConsistencyLevel eventual -All $skuId = (Get-MgSubscribedSku | Where-Object SkuPartNumber -eq 'ENTERPRISEPACK' ).SkuIdforeach ($user in $users ) { Set-MgUserLicense -UserId $user .Id ` -AddLicenses @ { SkuId = $skuId } ` -RemoveLicenses @ () Write-Host "已分配:$ ($user .DisplayName)" -ForegroundColor Green }
执行结果示例:
1 2 3 4 5 6 7 8 ------------ ---- ---- ------
注意事项
权限范围 :使用 -Scopes 参数指定最小必要权限,避免过度授权
ConsistencyLevel :部分高级查询需要添加 -ConsistencyLevel eventual 和 $Count 参数
分页处理 :大量结果时使用 -All 参数自动处理分页,否则只返回第一页
应用权限 :自动化脚本应使用应用权限(Client Credentials 流),而非用户委派权限
Graph API 版本 :MgGraph 模块默认使用 v1.0 端点,使用 Invoke-MgGraphRequest 可以调用 beta 端点
速率限制 :Microsoft Graph 有 API 调用频率限制,大批量操作时添加适当延迟