powershell - 处理cmdlet参数时出错?

标签 powershell error-handling active-directory powershell-3.0

我正在通过表单的用户输入在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=$AliasextensionAttribute4不能为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/

相关文章:

csv - PowerShell和CSV

c# - 在 PowerShell 中拆分、选择、加入

azure - Powershell - 设置环境变量而无需关闭应用程序

azure - Powershell + Azure 应用服务 + Azure 容器注册表

r - R创建缺少值的p值矩阵

error-handling - 在错误处理操作中如何确定我应该返回 web View 还是 api 响应

angular - 您如何捕捉错误

c# - 扩展用户主体; FindByIdentity() 失败

c# - 无法提取信息

c# - 事件目录服务 : PrincipalContext -- What is the DN of a "container" object?