【发布时间】:2018-05-25 11:22:54
【问题描述】:
我有一个代码块正在执行,它设置了一个简单的 If/Else 块来捕获错误。我通常会使用 Try/Catch,但我正在使用的 Exchange 2010 PS 环境不允许我使用大部分 Try/Catch 功能(而且我无法更新或以任何方式更改它,因为它是客户的系统,他们不愿意)。
问题是,当 Add-DistributionGroupMember cmdlet 设置为 -ErrorAction "Stop" 时,虽然代码将按预期运行,但它每次都会将错误输出到主机,这让客户(和我)很恼火,因为它是实际上只是红噪声,因为所有可能的错误都是通过详细的输出文件处理的。
如果我将 cmdlet 设置为 -ErrorAction "SilentlyContinue",则会抑制错误文本,但不会像我预期的那样将错误添加到 $Error[0] 位置。 -ErrorAction "Ignore" 也是如此。该代码要求每次出现错误时将Error添加到$Error变量中。
代码如下:
$ListMembershipsIn | % {
$Alias = $_.Alias
$Member = $_.Member
Add-DistributionGroupMember -Identity $Alias -Member $Member -Confirm:$false -ErrorAction Stop
if($Error[0] -match "The recipient"){
Write-Host -ForegroundColor Yellow "Already a member"
Add-Content -Path $OutputPath -Value "$($Alias),$($Member),Group already contains Member"
}
elseif($Error[0] -match "couldn't be found"){
Write-Host -ForegroundColor Yellow "not found"
Add-Content -Path $OutputPath -Value "Group does not exist or cannot be found,$($Alias),N/A"
}
elseif($Error[0] -match "couldn't find"){
Write-Host -ForegroundColor Yellow "not found"
Add-Content -Path $OutputPath -Value "Member does not exist or cannot be found,$($Alias),$($Member)"
}
elseif($Error[0] -match "There are Multiple"){
Add-Content -Path $OuputPath -Value "Member name matches too many recipient - Add Member Manually,$($Alias),$($Member)"
}
else{
Add-Content -Path $OutputPath -Value "Member Successfully Added to Group,$($Alias),$($Member)"
Write-Host -ForegroundColor Green "Throw Flag here"
}
}
【问题讨论】:
-
2010 年的产品可能正在使用 PowerShell 2.0。 PowerShell 3.0 出现在 Server 2012 中。想想客户留下的所有安全漏洞。 biztechmagazine.com/article/2017/01/…
-
幸运的是,所有这些工作都是为了将它们转移到 Exchange Online 中,以便他们摆脱所有这些旧服务器。我当然不会失去风险。
标签: powershell error-handling exchange-server