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

如何通过PowerShell批量将Entra/O365用户本地不可变ID设为$null

批量清除Entra ID用户的本地不可变ID(On-premises Immutable ID)

我需要批量将Entra ID(原O365)中用户的**On-premises immutable ID(本地不可变ID)**设置为$null。把用户从AD同步范围移除、恢复为仅云用户后,该字段未自动清除,引发同步错误。

之前尝试的操作

  • 通过PowerShell连接MS Graph导出用户数据:
    # Export All Users ImmutableIDs
    $Users = Get-MgUser -All -Property 'UserPrincipalName','OnPremisesImmutableId'
    $Users | Select-Object 'UserPrincipalName','OnPremisesImmutableId' | Export-Csv -Path "C:\TEMP\ExportUsersImmutableID.csv" -NoTypeInformation -Encoding UTF8
    
  • 使用Update-MgUser批量更新失败:设置$null时抛出「Invalid value」错误,仅字段非空时可正常执行:
    # Import .CSV and loop through users
    $csvData = Import-Csv "C:\TEMP\ExportUsersImmutableID.csv"
    foreach ($userRecord in $csvData) {
    Update-MgUser -UserId $userRecord.UserPrincipalName -OnPremisesImmutableId $userRecord.OnPremisesImmutableId 
    }
    
  • 改用Invoke-MgGraphRequest单个用户设置可行,但批量脚本执行时出现「{UserPrincipalName=fitter1@ausdraulics.com.au}不存在」错误,推测是URI错误包含字段标题;移除CSV的UserPrincipalName标题后无报错但未生效。

可行的批量处理脚本

Update-MgUser直接传入$null会触发API验证错误,需改用Invoke-MgGraphRequest发送PATCH请求,同时确保CSV格式正确(保留UserPrincipalName列标题)。

步骤1:整理CSV文件

保留CSV中的UserPrincipalName列即可,删除OnPremisesImmutableId列(我们要统一将该字段设为$null,无需读取原有值)。

步骤2:执行批量清除脚本

# 确保已连接MS Graph(提前执行 Connect-MgGraph -Scopes "User.ReadWrite.All")
$csvPath = "C:\TEMP\ExportUsersImmutableID.csv"
$csvData = Import-Csv $csvPath

foreach ($user in $csvData) {
    $userUpn = $user.UserPrincipalName
    $requestBody = @{
        onPremisesImmutableId = $null
    } | ConvertTo-Json

    try {
        Invoke-MgGraphRequest -Method PATCH `
                              -Uri "https://graph.microsoft.com/v1.0/users/$userUpn" `
                              -Body $requestBody `
                              -ContentType "application/json"
        Write-Host "✅ 已清除用户 $userUpn 的本地不可变ID"
    }
    catch {
        Write-Host "❌ 处理用户 $userUpn 失败: $($_.Exception.Message)"
    }
}

注意事项

  • 必须拥有User.ReadWrite.All权限,执行前用Connect-MgGraph -Scopes "User.ReadWrite.All"完成授权
  • 建议先选取1-2个测试用户验证脚本,确认无问题后再批量执行
  • CSV中不要包含多余列,避免解析错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:28:19