PowerShell创建AD用户:Mobile与ipPhone字段无法留空的解决求助
解决PowerShell创建AD用户时留空Mobile/ipPhone字段报错的问题
问题描述
此前运行正常的PowerShell创建AD用户脚本,近期无法通过直接回车将Mobile和ipPhone字段留空来继续执行,必须输入数字才能正常运行。但实际场景中有时无法预先获知这两个字段的信息,需要修改脚本实现回车留空、后续补充的功能。
原脚本
$Mobile = Read-Host "Type mobile number (leave blank and hit enter if you do not know the mobile number yet" $ipPhone = Read-Host "Indtast IpPhone number (leave blank and hit enter if you do not know the IpPhone number yet)" New-ADUser ` -Mobile "$Mobile" ` -OfficePhone "$Mobile" ` -OtherAttributes @{'ipPhone' = $ipPhone} `
报错信息
New-ADUser : 服务器不愿处理请求
At line:23 char:2
- New-ADUser `
+ CategoryInfo : NotSpecified: (CN=Jakob Hansen...faldvarme,DC=dk:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
问题原因
直接回车留空时,变量会被赋值为空字符串"",而Active Directory不接受将空字符串作为Mobile、ipPhone这类属性的值,因此服务器拒绝处理该请求。正确的做法是:当没有输入时,不对该属性进行设置(即传递$null而非空字符串)。
修改后的脚本
# 读取手机号码输入,留空则设为$null $MobileInput = Read-Host "输入手机号码(未知请直接回车)" $Mobile = if ([string]::IsNullOrWhiteSpace($MobileInput)) { $null } else { $MobileInput.Trim() } # 读取ipPhone号码输入,留空则设为$null $ipPhoneInput = Read-Host "输入ipPhone号码(未知请直接回车)" $ipPhone = if ([string]::IsNullOrWhiteSpace($ipPhoneInput)) { $null } else { $ipPhoneInput.Trim() } # 构建AD用户参数哈希表 $adUserParams = @{ # 请补充你的必填参数,例如: # Name = "Jakob Hansen" # SamAccountName = "jhansen" # UserPrincipalName = "jhansen@domain.dk" Mobile = $Mobile OfficePhone = $Mobile } # 仅当ipPhone有有效值时,添加到OtherAttributes if ($ipPhone -ne $null) { $adUserParams['OtherAttributes'] = @{'ipPhone' = $ipPhone} } # 执行创建AD用户操作 New-ADUser @adUserParams
关键修改说明
- 输入处理:用
[string]::IsNullOrWhiteSpace判断输入是否为空或仅含空白字符,若是则将变量设为$null,避免传递空字符串给AD。 - 参数动态构建:对于
OtherAttributes,仅当ipPhone有有效值时才将其加入参数哈希表,防止提交无效的空值属性。 - 参数传递:
New-ADUser接收到$null值的参数时,会跳过对应属性的设置,而非尝试写入空字符串,符合AD的要求。
内容的提问来源于stack exchange,提问作者user20510778
相关产品推荐
相关产品推荐

