gpt4 book ai didi

powershell - 处理cmdlet参数时出错?

转载 作者:行者123 更新时间:2023-12-03 09:03:12 24 4
gpt4 key购买 nike

我正在通过表单的用户输入在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com