如何通过PowerShell从CSV批量更新Azure AD租户内已有用户信息
PowerShell 批量更新租户用户属性脚本模板
前置依赖
- 已安装 Microsoft Graph PowerShell 模块,未安装可执行命令:
Install-Module Microsoft.Graph -Scope CurrentUser -Force - 连接租户时需配置足够权限,连接命令:
Connect-MgGraph -Scopes "User.ReadWrite.All" - 已完成CSV文件导入逻辑,CSV内必须包含
UserPrincipalName列,用于唯一匹配租户内的目标用户
CSV文件格式要求
你可以参考如下结构整理你的员工列表CSV,列名建议和属性名保持一致,避免映射错误:
UserPrincipalName,fax,office,StreetAddress,city,postalcode,department,title,officephone,mobilephone,mail zhangsan@contoso.onmicrosoft.com,010-12345678,中关村西区,海淀路100号,北京,100080,技术部,高级工程师,010-87654321,13800138000,zhangsan@contoso.com lisi@contoso.onmicrosoft.com,021-12345678,陆家嘴,浦东南路500号,上海,200120,市场部,市场经理,021-87654321,13900139000,lisi@contoso.com
注意:原需求中拼写的
streetadress为错误写法,标准属性名为StreetAddress,请同步修正CSV列名
完整执行脚本
# 1. 导入CSV文件,替换为你本地的CSV文件路径 $userList = Import-Csv -Path "C:\你的员工列表路径\员工信息.csv" -Encoding UTF8 # 2. 遍历CSV内的每一行用户信息,执行更新操作 foreach ($user in $userList) { # 校验当前用户是否在租户内存在 $targetUser = Get-MgUser -UserId $user.UserPrincipalName -ErrorAction SilentlyContinue if ($null -eq $targetUser) { Write-Host "未找到用户:$($user.UserPrincipalName),跳过更新" -ForegroundColor Yellow continue } # 组装要更新的属性参数 $updateParams = @{ FaxNumber = $user.fax OfficeLocation = $user.office StreetAddress = $user.StreetAddress City = $user.city PostalCode = $user.postalcode Department = $user.department JobTitle = $user.title BusinessPhones = @($user.officephone) MobilePhone = $user.mobilephone Mail = $user.mail } # 执行更新操作 try { Update-MgUser -UserId $user.UserPrincipalName @updateParams -ErrorAction Stop Write-Host "用户:$($user.UserPrincipalName) 更新成功" -ForegroundColor Green } catch { Write-Host "用户:$($user.UserPrincipalName) 更新失败,错误信息:$_" -ForegroundColor Red } }
使用注意事项
- 首次执行建议先注释掉
Update-MgUser相关代码,只输出$updateParams的内容确认属性映射正确,避免误改用户信息 - 如果你需要保留用户原有不为空的属性,只覆盖CSV中存在值的字段,可以在组装
$updateParams前添加非空判断,过滤掉CSV中为空的字段 - 执行完成后可通过命令
Get-MgUser -UserId <用户主体名称> | Select-Object FaxNumber,OfficeLocation,StreetAddress,City,PostalCode,Department,JobTitle,BusinessPhones,MobilePhone,Mail验证更新结果
内容的提问来源于stack exchange,提问作者David G.
相关产品推荐
相关产品推荐

