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

Microsoft Graph脚本无法更新Entra用户:无报错但无变更

问题:PowerShell脚本通过Microsoft Graph批量更新Entra用户无报错但未生效

已配置User.ReadWrite、Group.ReadWrite权限连接Microsoft Graph,执行批量更新用户的PowerShell脚本后无任何错误提示,但Entra/M365中用户属性未发生实际变更。脚本读取CSV文件批量更新,期望完成属性修改,但未产生效果。

原使用脚本

<#
.Purpose
   This script updates user information in Entra using data from a CSV file via Microsoft Graph.
   It is designed for bulk updates, allowing you to modify multiply user properties at once.
  
.Notes 
  *Requires the Microsoft.Graph.Users module to be installed (Uncomment the command to install).
  *Requires the Microsoft.Graph.Authentication module to be installed (Uncomment the command to install). 
  *The CSV file should contain a header row with column names that matches the Microsoft Graph User Properties that you want to update. 
  *The UserPrincipalName is used to identify the user to update. Make sure this is accurate in your CSV. 
  *This script requires the User.ReadWrite.All scope. Modify the script and scope to meet least privilege.

.Inputs
  None

.Outputs
  Success or error messages for each user update
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true, HelpMessage = "The path to the CSV file containing the user data.")]
    [string]$CSVFilePath
    )

#Install the Microsoft Graph Users module if needed
if (-not (Get-Module -Name Microsoft.Graph.Users)) {

     Write-Host "Now Installing the Microsoft Graph User Module..."
     Install-Module -Name Microsoft.Graph.Users -ErrorAction Stop
}   

#Install the Microsoft Graph Authenticator module if needed
if (-not(Get-Module -Name Microsoft.Graph.Authentication)) {

     Write-Warning "Now Installing the Microsoft Graph Authenticator..."
     Install-Module -Name Microsoft.Graph.Authentication -Scope CurrentUser -Force
}   

#Connect to Microsoft Graph PowerShell module
if (-not (Get-MgContext)) {
    try {
        Write-Host "Connecting to Microsoft Graph..."
        Connect-MgGraph -Scopes "User.ReadWrite.All"
    }
    catch {
        Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
       exit 1
    }
}

#Import the CSV file

try {
    $UsersToUpdate = Import-Csv -Path $CSVFilePath
} catch {
       Write-Error "Failed to import CSV file: $($_.Exception.Message)"
       exit 1
}


# Iterate through each user in the CSV
foreach ($user in $users) {

    # Get the user object from Microsoft Entra ID 

    $userObject = Get-MgUser -Filter "userPrincipalName eq '$(user.UserPrincipalName)'" 
 
    if (userObject) { 
        #Build a hashtable for attributes to update
  
        $userProperties = @{}

        # Add properties into hash table
    
        if ($user.DiplayName) { 
            $userProperties["fistName"] = $user.FirstName 
        }
     
        if ($user.LastName) {
            $userProperties["lastName"] = $user.LastName
        }
    
        if ($user.Department) {
            $userProperties["department"] = $user.Department
        }

        if ($user.JobTitle) {
            $userProperties["jobTitle"] = $user.JobTitle
        }

        if ($user.Country) {
            $userProperties["country"] = $user.Country
        }
    
        if ($user.City) { 
            $userProperties["city"] = $user.City
        }
    
        if ($user.State) {
            $userProperties["state"] = $user.State
        }

        if ($user.StreetAddress) {
            $userProperties["StreetAddress"] = $user.StreetAddress
        }
     
        # Update the users properties using Update-MgUser

        try {
            Update-Mguser -UserId $userObject.Id -BodyParameter $userProperties
            Write-Host "Updated user: $($users.UserPrincipalName)"
        }
        catch { 
            Write-Error "Failed to update user"
        }
     
     else {
        Write-Host "No properties to update for user: $($users.UserPrincipalName)"
     }
    
     else { 
        Write-Host "User not found: $($users.UserPrincipalName)"
     }
   }
}     
      

Write-Host "Script completed."

错误分析及修复方案

脚本无报错但未生效,核心是存在多处语法错误、变量引用错误和API属性不匹配问题:

1. 变量引用错误

  • 多处未加$符号:user.UserPrincipalName → $user.UserPrincipalName;userObject → $userObject
  • 循环变量混淆:foreach中定义的是$user,后续错误使用$users(如$users.UserPrincipalName)

2. 拼写错误

  • DiplayName → DisplayName(CSV列名和判断条件需统一)
  • fistName → firstName(Graph API属性名拼写错误)

3. API属性大小写不匹配

Graph API用户属性采用驼峰式命名,StreetAddress → streetAddress

4. 语法结构错误

原脚本if-else嵌套逻辑混乱,else位置错误导致代码块未正确执行

5. 权限问题

User.ReadWrite权限仅允许更新当前用户,批量更新其他用户需User.ReadWrite.All或Directory.AccessAsUser.All权限

修复后的完整脚本

<#
.Purpose
   批量更新Entra用户信息,通过CSV文件导入数据并调用Microsoft Graph API
.Notes 
  *需安装Microsoft.Graph.Users和Microsoft.Graph.Authentication模块
  *CSV文件需包含UserPrincipalName列用于定位用户,其他列名需匹配Graph API用户属性
  *需User.ReadWrite.All或Directory.AccessAsUser.All权限
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true, HelpMessage = "CSV文件路径")]
    [string]$CSVFilePath
)

# 安装所需模块
if (-not (Get-Module -Name Microsoft.Graph.Users -ListAvailable)) {
    Write-Host "正在安装Microsoft.Graph.Users模块..."
    Install-Module -Name Microsoft.Graph.Users -Scope CurrentUser -Force -ErrorAction Stop
}

if (-not (Get-Module -Name Microsoft.Graph.Authentication -ListAvailable)) {
    Write-Warning "正在安装Microsoft.Graph.Authentication模块..."
    Install-Module -Name Microsoft.Graph.Authentication -Scope CurrentUser -Force -ErrorAction Stop
}

# 连接Microsoft Graph
if (-not (Get-MgContext)) {
    try {
        Write-Host "正在连接Microsoft Graph..."
        Connect-MgGraph -Scopes "User.ReadWrite.All" -ErrorAction Stop
    }
    catch {
        Write-Error "连接失败: $($_.Exception.Message)"
        exit 1
    }
}

# 导入CSV数据
try {
    $UsersToUpdate = Import-Csv -Path $CSVFilePath -ErrorAction Stop
}
catch {
    Write-Error "导入CSV失败: $($_.Exception.Message)"
    exit 1
}

# 遍历用户执行更新
foreach ($user in $UsersToUpdate) {
    # 验证UserPrincipalName是否存在
    if (-not $user.UserPrincipalName) {
        Write-Warning "CSV中缺少UserPrincipalName,跳过当前行"
        continue
    }

    # 获取Entra中的用户对象
    try {
        $userObject = Get-MgUser -Filter "userPrincipalName eq '$($user.UserPrincipalName)'" -ErrorAction Stop
    }
    catch {
        Write-Error "查询用户失败 $($user.UserPrincipalName): $($_.Exception.Message)"
        continue
    }

    if ($userObject) {
        $userProperties = @{}

        # 构建更新属性哈希表
        if ($user.FirstName) {
            $userProperties["firstName"] = $user.FirstName
        }
        if ($user.LastName) {
            $userProperties["lastName"] = $user.LastName
        }
        if ($user.Department) {
            $userProperties["department"] = $user.Department
        }
        if ($user.JobTitle) {
            $userProperties["jobTitle"] = $user.JobTitle
        }
        if ($user.Country) {
            $userProperties["country"] = $user.Country
        }
        if ($user.City) {
            $userProperties["city"] = $user.City
        }
        if ($user.State) {
            $userProperties["state"] = $user.State
        }
        if ($user.StreetAddress) {
            $userProperties["streetAddress"] = $user.StreetAddress
        }

        # 执行更新
        if ($userProperties.Count -gt 0) {
            try {
                Update-MgUser -UserId $userObject.Id -BodyParameter $userProperties -ErrorAction Stop
                Write-Host "成功更新用户: $($user.UserPrincipalName)"
            }
            catch {
                Write-Error "更新用户失败 $($user.UserPrincipalName): $($_.Exception.Message)"
            }
        }
        else {
            Write-Host "用户 $($user.UserPrincipalName) 无需要更新的属性"
        }
    }
    else {
        Write-Host "未找到用户: $($user.UserPrincipalName)"
    }
}

Write-Host "脚本执行完成"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:17:02