请求编写MS Graph/PowerShell脚本批量修改所有用户使用位置为CA
批量修改所有用户使用位置为CA的PowerShell脚本(基于Microsoft Graph)
前提条件
- 安装Microsoft Graph PowerShell模块:
Install-Module Microsoft.Graph.Users - 拥有User.ReadWrite.All权限
- 已连接到Microsoft Graph:
Connect-MgGraph -Scopes "User.ReadWrite.All"
批量修改脚本
# 设置目标使用位置 $targetUsageLocation = 'CA' # 获取所有用户(可按需添加过滤条件) $allUsers = Get-MgUser -All $true -Select Id, UserPrincipalName, UsageLocation # 循环更新每个用户的使用位置 foreach ($user in $allUsers) { # 跳过已设置为目标位置的用户,减少无效请求 if ($user.UsageLocation -eq $targetUsageLocation) { Write-Host "用户 $($user.UserPrincipalName) 已设置使用位置为CA,跳过" continue } try { Update-MgUser -UserId $user.Id -UsageLocation $targetUsageLocation Write-Host "成功更新用户 $($user.UserPrincipalName) 的使用位置为CA" } catch { Write-Error "更新用户 $($user.UserPrincipalName) 失败:$_" } }
额外说明
- 若仅需更新启用状态的用户,可修改
Get-MgUser命令为:Get-MgUser -All $true -Filter "AccountEnabled eq true" -Select Id, UserPrincipalName, UsageLocation -Select参数用于指定仅获取必要属性,减少数据传输量- 错误处理逻辑会输出更新失败的用户及具体原因,方便排查问题
内容的提问来源于stack exchange,提问作者user23470524
相关产品推荐
相关产品推荐

