使用New-ADUser遇参数重复绑定及位置参数错误求助
解决New-ADUser参数重复/位置参数错误的问题
我来帮你搞定这个问题!你遇到的这两个错误本质上是同一个原因:当使用-Instance参数传递模板用户对象时,不能同时手动指定已经存在于模板对象中的属性参数,而且-co和-Country其实是AD用户属性Country/Region的两个参数别名,属于同一个参数,重复指定就会触发第一个错误;移除其中一个后,模板里的属性和你手动指定的仍然冲突,PowerShell会把无法匹配的参数当成位置参数,于是出现第二个错误。
正确的解决思路
不要在New-ADUser里同时混用-Instance和模板已有的属性参数,而是先复制模板对象,在循环里修改模板对象的属性值,再传递给New-ADUser。这样既保留了模板的便捷性,又不会出现参数冲突。
修正后的脚本
$NORMAL_ACCOUNTS = Import-Excel -Path "data_norm.xlsx" # 获取模板用户,可按需筛选必要属性提升效率 $TEMPLATE_NORMAL_ACCOUNT = Get-ADUser anUser -Properties c, co, Company, Description, DisplayName, employeeType, GivenName, Manager, Organization, otherMailbox, preferredLanguage, PrimaryGroup, SamAccountName, sn, StreetAddress, Title, UserPrincipalName $TEMPLATE_NORMAL_ACCOUNT.UserPrincipalName = $NULL FOREACH($NORMAL in $NORMAL_ACCOUNTS) { # 复制模板对象,避免修改原模板影响后续循环 $newUserTemplate = $TEMPLATE_NORMAL_ACCOUNT.PSObject.Copy() # 逐个修改模板对象的属性 $newUserTemplate.c = $NORMAL.c $newUserTemplate.co = $NORMAL.co $newUserTemplate.Company = $NORMAL.Company $newUserTemplate.Description = $NORMAL.Description $newUserTemplate.DisplayName = $NORMAL.DisplayName $newUserTemplate.employeeType = $NORMAL.employeeType $newUserTemplate.GivenName = $NORMAL.GivenName $newUserTemplate.Manager = $NORMAL.Manager $newUserTemplate.Organization = $NORMAL.Organization $newUserTemplate.otherMailbox = @($NORMAL.otherMailbox) $newUserTemplate.preferredLanguage = $NORMAL.preferredLanguage $newUserTemplate.PrimaryGroup = $NORMAL.PrimaryGroup $newUserTemplate.SamAccountName = $NORMAL.SamAccountName $newUserTemplate.sn = $NORMAL.sn $newUserTemplate.StreetAddress = $NORMAL.StreetAddress $newUserTemplate.Title = $NORMAL.Title $newUserTemplate.UserPrincipalName = $NORMAL.UserPrincipalName # 调用New-ADUser,仅传递修改后的模板和模板未包含的参数 New-ADUser ` -Instance $newUserTemplate ` -AccountPassword (Read-Host -AsSecureString "INPUT USER PASSWORD") ` -Enabled $FALSE }
关键说明
- 使用
$TEMPLATE_NORMAL_ACCOUNT.PSObject.Copy()复制模板对象,确保每次循环都是独立的对象,不会互相干扰。 - 所有从Excel读取的属性直接赋值给复制后的模板对象,不再手动在
New-ADUser里指定这些参数,彻底避免参数冲突。 - 仅保留
-Instance和模板中没有的参数(比如-AccountPassword、-Enabled),这些参数不会和模板属性产生冲突。
这样修改后,就不会再出现参数重复或者位置参数找不到的错误了。
内容的提问来源于stack exchange,提问作者Daycopo
相关产品推荐
相关产品推荐

