我正在通过表单上的用户输入在AD上创建新用户。
New-ADUser -Name $ADName -UserPrincipalName $UPN -SamAccountName $SAM -AccountPassword $Password -City $City -Country $Country `
-Department $Department -Description $EmployeeNum -DisplayName $displayName -Division $Division -EmailAddress $Email -EmployeeNumber $EmployeeNum -GivenName $firstName `
-Initials $MiddleInit -Office $CSCSuffix -OfficePhone $PhoneExt -PostalCode $Zipcode -State $State -StreetAddress $Street -Surname $LastName -Title $JobTitle`
-OtherAttributes @{extensionAttribute1=$OfficePhone;extensionAttribute4=$Alias} -ErrorAction SilentlyContinue
New-ADUser
命令有很多参数,如果其中一个参数无效,则会抛出整个New-ADUser
命令。
总有没有忽略错误的参数并继续执行父命令(包括所有其他有效参数)吗?
例如,extensionAttribute4=$Alias
。 extensionAttribute4
不能为null。如果用户将$Alias
留空,则该命令将中断并且不会创建一个新用户,尽管其他所有参数均有效。
我尝试了-ErrorAction SilentlyContinue
,但这没用,因为那只是命令本身。我以为我可以做这项工作的唯一方法就是这样做:
New-ADUser -Name $ADName
Set-ADUser -Identity $ADName -Department $Department -ErrorAction SilentlyContinue
Set-ADUser -Identity $ADName -OfficePhone $PhoneExt -ErrorAction SilentlyContinue
Set-ADUser -Identity $ADName -OtherAttributes @{extensionAttribute1=$OfficePhone} -ErrorAction SilentlyContinue
Set-ADUser -Identity $ADName -OtherAttributes @{extensionAttribute4=$Alias} -ErrorAction SilentlyContinue
....
我想这样做对错误处理-OtherAttributes
会很好,因为它是一个哈希表,但是这样做并不理想。
答案 0 :(得分:3)
您可以改为向cmdlet提供参数表,以便可以在提供参数之前测试null。例如:
$parameters = @{}
# add your mandatory parameters
$parameters["SamAccountName"] = $SamAccountName
# ...
if (-not [String]::IsNullOrWhiteSpace($department))
{
$parameters["Department"] = $department
}
# ...
New-ADUser @parameters