如何使用PowerShell添加带自定义属性的AD账户?
解决New-AdUser设置自定义AD属性报错的问题
你遇到的这个New-AdUser参数错误(错误代码87),核心原因大概率是自定义属性的LDAP显示名不匹配,或者属性的使用约束没满足——毕竟你已经完成架构扩展且能在属性编辑器看到该属性,说明架构层面是没问题的,下面一步步帮你排查解决:
1. 确认自定义属性的LDAP显示名
ADUC属性编辑器里的友好名称,和PowerShell要求的LDAP显示名可能不一样,这是最常见的踩坑点:
- 打开ADSI编辑器,右键选择「连接到」,命名上下文选
Schema; - 在Schema节点下找到你扩展的属性对象,查看它的
ldapDisplayName属性值——这个值才是你要放到otherAttributes哈希表中的键。
比如如果属性的LDAP显示名是testAttr,那哈希表要写成@{'testAttr' = "testval"},而不是用属性编辑器里的友好名称。
2. 检查属性语法与赋值方式
如果你的自定义属性是多值属性(允许存储多个值),赋值时需要用数组格式:
$otherAttributes = @{'test' = @("testval1", "testval2")}
单值属性直接赋值字符串即可,但如果属性语法是整数、二进制等类型,要传入对应类型的值,不能用字符串硬转。
3. 修正后的完整代码示例
假设你确认LDAP显示名就是test,可以用下面的规范代码尝试:
$pw = "jakdakjdJAKJKA123" $spw = ConvertTo-SecureString $pw -AsPlainText -Force $accountname = "mytest" $des = "Description" # 确保键是属性的LDAP显示名 $otherAttributes = @{'test' = "testval"} New-AdUser -UserPrincipalName "$accountname@testdomain.local" ` -Path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" ` -Name "$accountname" ` -SamAccountName "$accountname" ` -GivenName "$accountname" ` -Description $des ` -CannotChangePassword $true ` -DisplayName "$accountname" ` -PasswordNeverExpires $true ` -AccountPassword $spw ` -Enabled $true ` -OtherAttributes $otherAttributes
4. 备选方案:创建用户后再设置属性
如果还是遇到问题,可以拆分步骤:先创建用户,再用Set-AdUser单独设置自定义属性,这种方式更易排查问题:
# 先创建用户(去掉otherAttributes参数) New-AdUser -UserPrincipalName "$accountname@testdomain.local" ` -Path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" ` -Name "$accountname" ` -SamAccountName "$accountname" ` -GivenName "$accountname" ` -Description $des ` -CannotChangePassword $true ` -DisplayName "$accountname" ` -PasswordNeverExpires $true ` -AccountPassword $spw ` -Enabled $true # 再设置自定义属性 Set-AdUser -Identity $accountname -Replace @{'test' = "testval"}
5. 最后排查:确认属性是否允许在用户对象上使用
虽然你在属性编辑器里能看到该属性,还是要确认架构扩展时,属性被添加到了user类的mayContain或mustContain属性中:
- 在ADSI编辑器的Schema节点下找到
user类对象,查看mayContain属性列表,确保包含你的自定义属性的LDAP显示名。如果没有,需要重新修改架构扩展,把属性添加到用户类的允许属性列表里。
内容的提问来源于stack exchange,提问作者ro ra
相关产品推荐
相关产品推荐

