使用PowerShell更新用户多值属性msExchExtensionCustomAttribute2失败求助
解决Set-ADUser更新多值属性msExchExtensionCustomAttribute2的类型错误
错误原因
msExchExtensionCustomAttribute2是Active Directory的多值属性,使用Set-ADUser的-Add参数时,要求传入数组类型的值。你当前的循环中每次传入单个字符串变量$i,PowerShell会将其包装为PSObject,导致类型不匹配报错。
修复方案
方案1:一次性传入所有值(推荐)
直接读取文件内容为数组,一次性添加到多值属性,减少AD交互次数,效率更高:
# 读取文件所有内容为数组 $customValues = Get-Content C:\temp\test.txt # 一次性添加到多值属性 Set-ADUser "test" -Add @{msExchExtensionCustomAttribute2 = $customValues}
方案2:循环添加(需强制转数组)
如果需要逐行处理(比如过滤空行),要将单个值强制转为数组类型:
foreach ($value in (Get-Content C:\temp\test.txt)) { # 跳过空行 if ([string]::IsNullOrWhiteSpace($value)) { continue } # 用@()将单个值转为数组,符合多值属性类型要求 Set-ADUser "test" -Add @{msExchExtensionCustomAttribute2 = @($value)} }
额外提示
- 若需要覆盖原有属性值而非追加,将
-Add替换为-Replace即可。 - 操作前建议用
Get-ADUser "test" -Properties msExchExtensionCustomAttribute2查看当前属性值,确认修改效果。
内容的提问来源于stack exchange,提问作者Dhiman Sau
相关产品推荐
相关产品推荐

