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

批量修改AD用户EmployeeID失败,请求解决方案

批量修改Active Directory用户EmployeeID的问题解决

问题场景

需要批量更新AD用户的EmployeeID,变量$ke存储了用户名与对应EmployeeID的映射关系,内容如下:

EmployeeID  Employee
00000122    username1
00000100    username2

错误尝试及原因分析

第一次错误代码

$username = $ke.Employee
foreach($user in $username) {
   Set-ADUser $user -EmployeeID "$ke.EmployeeID"
}

报错信息:

Set-ADUser : A value for the attribute was not in the acceptable range of values
At line:2 char:4
Set-ADUser $user -EmployeeID '$ke.EmployeeID'

+ CategoryInfo          : NotSpecified: (username1:ADUser) [Set-ADUser], ADException  
+ FullyQualifiedErrorId : ActiveDirectoryServer:8322,Microsoft.ActiveDirectory.Management.Commands.SetADUser

原因:双引号内的$ke.EmployeeID会被解析为整个集合的EmployeeID属性的字符串形式(类似System.Object[]),并非当前用户对应的单个有效ID,AD无法识别该无效值。

第二次错误代码

$username = $ke.Employee

foreach($user in $username) { 
   Set-ADUser $user -EmployeeID $ke.EmployeeID
}

报错信息:

Set-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'EmployeeID'. Specified
method is not supported.
At line:2 char:33
Set-ADUser $user -EmployeeID $ke.EmployeeID

+ CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException  
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.SetADUser

原因:$ke.EmployeeID是包含所有ID的数组,而Set-ADUser的-EmployeeID参数要求传入单个字符串,类型不匹配导致报错。

正确解决方案

直接遍历$ke集合中的每个条目,确保每个用户名对应正确的EmployeeID:

foreach($entry in $ke) {
    # 可选:先验证AD用户是否存在,避免无效操作
    $adUser = Get-ADUser -Filter "SamAccountName -eq '$($entry.Employee)'" -ErrorAction SilentlyContinue
    if($adUser) {
        Set-ADUser $adUser -EmployeeID $entry.EmployeeID
        Write-Host "已更新用户 $($entry.Employee) 的EmployeeID为 $($entry.EmployeeID)"
    } else {
        Write-Warning "未找到AD用户 $($entry.Employee)"
    }
}

关键说明

  • 遍历完整的$ke条目而非单独的用户名数组,保证用户名与EmployeeID的对应关系不脱节
  • 加入用户存在性验证,减少无意义的报错
  • $entry.EmployeeID直接获取当前条目的单个ID值,完全符合Set-ADUser参数的类型要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:26:20