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

New-ADUser脚本处理serialnumber空值报错问题求助

解决New-ADUser脚本中serialnumber为空时的报错问题

这个问题很常见——当CSV里的serialnumber字段为空时,你直接把它塞进OtherAttributes哈希表,PowerShell会把空值传递给New-ADUser,而AD不接受serialNumber属性为null或空字符串,所以就触发了报错。下面给你两种可靠的解决思路:

方法一:仅在serialnumber有值时添加OtherAttributes

先构建基础的用户属性哈希表,然后判断$User.serialnumber是否有效,再决定是否添加OtherAttributes键:

# 先创建不含serialNumber的基础哈希表
$hashtable = @{
    Name              = $User.Surname + " " + $User.Givenname
    Surname           = $User.Surname
    Givenname         = $User.Givenname
    Samaccountname    = $User.Samaccountname
    Emailaddress      = $User.Emailaddress
    Accountpassword   = $User.password | ConvertTo-SecureString -AsPlainText -Force
    Path              = $User.Path
    UserPrincipalName = $User.Samaccountname + "@anything.com"
}

# 仅当serialnumber非空且非空白时,添加OtherAttributes
if (-not [string]::IsNullOrWhiteSpace($User.serialnumber)) {
    $hashtable['OtherAttributes'] = @{ serialNumber = $User.serialnumber }
}

# 执行创建用户操作
New-ADUser @hashtable

方法二:如果OtherAttributes还有其他属性,动态添加serialNumber

如果你的OtherAttributes里还需要包含其他AD属性,可以先初始化一个空的哈希表,再根据情况添加serialNumber:

# 初始化包含空OtherAttributes的哈希表
$hashtable = @{
    Name              = $User.Surname + " " + $User.Givenname
    Surname           = $User.Surname
    Givenname         = $User.Givenname
    Samaccountname    = $User.Samaccountname
    Emailaddress      = $User.Emailaddress
    Accountpassword   = $User.password | ConvertTo-SecureString -AsPlainText -Force
    Path              = $User.Path
    UserPrincipalName = $User.Samaccountname + "@anything.com"
    OtherAttributes   = @{}
}

# 仅当serialnumber有效时,添加到OtherAttributes
if (-not [string]::IsNullOrWhiteSpace($User.serialnumber)) {
    $hashtable['OtherAttributes']['serialNumber'] = $User.serialnumber
}

# 执行创建用户操作
New-ADUser @hashtable

关键说明

我用[string]::IsNullOrWhiteSpace()来判断值是否有效,这个方法能覆盖CSV里可能出现的null、空字符串、纯空格等情况,比单纯判断$User.serialnumber -ne $null更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:26:12