Powershell - try/catch in foreach



此代码在Catch块中写入错误并停止执行

$Result=""   
$Results=@() 

$Customers = Get-PartnerCustomer
Try{
$Customers.ForEach({
$CustId = $_.CustomerId
$CustName =$_.Name
$CustomerUser = Get-PartnerCustomerUser -CustomerId $CustId | Where-Object {
$_.DisplayName -like 'name'
} | ForEach-Object {
$_.DisplayName
#$_.UserPrincipalName
}
$Result=@{'Customer Name'=$CustName;'User Name'=$CustomerUser}
$Results+= New-Object PSObject -Property $Result

})
}
Catch{
Write-Warning "Caught an exception:"
Write-Warning "Exception Type: $($_.Exception.GetType().FullName)"
Write-Warning "Exception Message: $($_.Exception.Message) - Tenant:$CustName"
}

当在顶部脚本添加$ErrorActionPreference="Continue"时,错误之后继续,但写入通用错误消息

Get-PartnerCustomerUser : Access denied.
At line:8 char:33
+ ...   $CustomerUser = Get-PartnerCustomerUser -CustomerId $CustId | Where ...
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : CloseError: (:) [Get-PartnerCustomerUser], PartnerException
+ FullyQualifiedErrorId : Microsoft.Store.PartnerCenter.PowerShell.Commands.GetPartnerCustomerUser

对于$ErrorActionPreference="SilentlyContinue",它不输出任何错误。

是否有可能显示我的自定义错误消息,而不是在第一个错误时退出循环?

解决了,必须在ForEach里面添加Try/Catch

$ErrorActionPreference="Stop"
$Customers = Get-PartnerCustomer
$Customers.ForEach({
Try{
$CustId = $_.CustomerId
$CustName =$_.Name
$CustomerUser = Get-PartnerCustomerUser -CustomerId $CustId | Where-Object {
$_.DisplayName -like 'Name'
} | ForEach-Object {
$_.DisplayName
#$_.UserPrincipalName
}
$Result=@{'Customer Name'=$CustName;'User Name'=$CustomerUser}
$Results+= New-Object PSObject -Property $Result

}

Catch{
Write-Warning "Caught an exception:"
Write-Warning "Exception Type: $($_.Exception.GetType().FullName)"
Write-Warning "Exception Message: $($_.Exception.Message) - Tenant:$CustName"
}
}
)

最新更新