如何使用下面的 Try/catch 块实际捕获找不到的电子邮件地址?



下面的代码将根据 https://learn.microsoft.com/en-us/powershell/module/exchange/get-exorecipient?view=exchange-ps 根据Exchange Online检查多行电子邮件地址

Try {
Clear
$EmailAliases = @(
'Myself.actual@domain.com'
'Good.Boss@domain.org'
'fake.person1@domain.org'
'fake.person2@domain.org'
)
$EmailAliases | Get-EXORecipient | Select Name, RecipientType, @{Label = 'Email Address'; Expression = {($_.EmailAddresses | Where-Object {($_ -like 'SMTP*') -and ($_ -notlike '*onmicrosoft.com') } | Sort-Object -CaseSensitive -Descending | ForEach-Object {$_.Split(':')[1]}) -join ', ' }} | Out-GridView
}
Catch {
Write-Warning -Message "The email address $($EmailAliases) cannot be found"
Write-Warning -Message $Error[0].Exception.Message
$out.Details = $_.Exception.Message
Write-Host " ERROR: $($out.Details)" -ForegroundColor Red
}

但是,如果找不到电子邮件地址,则会抛出错误

错误代码:

Get-EXORecipient : Error while querying REST service. HttpStatusCode=404 ErrorMessage={"error":{"code":"NotFound","message":"Error executing request. 
","details":[{"code":"Context","target":"","message":"Ex6F9304|Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException|The operation couldn't be performed because object 'Fake.person1@domain.org' couldn't be found on 
'NY2PR01A001DC02.NAMPR01A001.PROD.OUTLOOK.COM'."}],"innererror":{"message":"Error executing request. ","type":"Microsoft.Exchange.Admin.OData.Core.ODataServiceException"}}}}
At line:11 char:18
+     $EmailAliases | Get-EXORecipient | Select Name, RecipientType, @{ ...
+                     ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ProtocolError: (:) [Get-EXORecipient], RestClientException
+ FullyQualifiedErrorId : An error occurred while processing this request.,Microsoft.Exchange.Management.RestApiClient.GetExoRecipient

Get-EXORecipient上的Identity参数接受单个项目,而不是电子邮件地址数组,所以我相信你需要一个循环来做到这一点.
此外,你在Try{}做了不应该存在的事情,比如定义要测试的电子邮件地址数组。这是在进入try{}..catch{}正在做其工作的循环之前完成的。

尝试:

Clear-Host
$EmailAliases = 'Myself.actual@domain.com', 'Good.Boss@domain.org',
'fake.person1@domain.org', 'fake.person2@domain.org'
$result = foreach ($eml in $EmailAliases) {
Try {
Get-EXORecipient -Identity $eml -ErrorAction Stop | 
Select-Object Name, RecipientType, 
@{Name = 'Email Address'; Expression = {
($_.EmailAddresses | 
Where-Object { ($_ -like 'SMTP*') -and ($_ -notlike '*onmicrosoft.com') } | 
Sort-Object -CaseSensitive -Descending | 
ForEach-Object { $_ -replace '^smtp:'}) -join ', ' }
},
@{Name = 'Details'; Expression = { 'OK' }}
}
Catch {
# inside the Catch block, the $_ automatic variable is the exception object
Write-Warning -Message "The email address $eml cannot be found"
$err = $_.Exception.Message
Write-Warning -Message $err
# output a similar object as in the catch block showing the failed email address
"" | Select-Object @{Name = 'Name'; Expression = { 'Not found' }}, RecipientType,
@{Name = 'Email Address'; Expression = { $eml }},
@{Name = 'Details'; Expression = { $err }}
}
}
$result | Out-GridView

最新更新