我正在通过表单的用户输入在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
会很好,因为它是一个哈希表,但否则并不理想。
最佳答案
您可以向cmdlet提供参数表,以便可以在提供参数之前测试null。例如:
$parameters = @{}
# add your mandatory parameters
$parameters["SamAccountName"] = $SamAccountName
# ...
if (-not [String]::IsNullOrWhiteSpace($department))
{
$parameters["Department"] = $department
}
# ...
New-ADUser @parameters
关于powershell - 处理cmdlet参数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678221/