PowerShell调用Exchange Set-Contact报错未触发catch块的处理方法
解决方法
首先明确问题根本原因:PowerShell的错误分为终止错误和非终止错误两类,默认只有终止错误才会触发try/catch逻辑,Exchange的Set-Contact这类cmdlet默认抛出的参数错误、执行错误都属于非终止错误,所以不会进入你写的catch块。
你可以通过以下两种方式实现需求:
方案1:仅针对Set-Contact命令强制转终止错误(推荐,影响范围最小)
在Set-Contact命令末尾添加-ErrorAction Stop参数,即可将该命令的所有错误转为终止错误,直接触发catch块。
修改后的命令示例:
Set-Contact -Identity $msxchangeInfo.Identity -CountryOrRegion $officeCountry -ErrorAction Stop
注意:你原代码中存在变量笔误,你定义的变量是
$msxchangeInfo,但使用了不存在的$msxchangeInfoIdentity,需要修正为$msxchangeInfo.Identity才能正常取到联系人标识。
方案2:全局修改错误处理策略(适合整段try块内所有命令都需要捕获错误的场景)
在try块开头修改全局错误处理策略,将所有非终止错误默认转为终止错误,为了避免影响后续脚本逻辑,建议在finally块中恢复默认配置:
try{ # 先保存原有配置 $originalErrorAction = $ErrorActionPreference $ErrorActionPreference = 'Stop' # 原有业务逻辑 $msxchangeInfo = Get-Contact | Where-Object {$_.WindowsEmailAddress -eq "$user_search_email"} if ($msxchangeInfo) { write-host "$(Get-TimeStamp) $user_search_email found...." $msxchangeInfo = Get-Contact -Filter "WindowsEmailAddress -eq '$($user_search_email)'" | Select-Object -Property WindowsEmailAddress, Manager, FirstName, LastName, MobilePhone, DisplayName, Company, Department, Identity, StreetAddress, StateOrProvince, PostalCode, CountryOrRegion, City, Phone $msxchangeInfoCountryOrRegion = $msxchangeInfo | Select -ExpandProperty CountryOrRegion if($msxchangeInfoCountryOrRegion -ne $officeCountry -and $officeCountry -ne "") { Set-Contact -Identity $msxchangeInfo.Identity -CountryOrRegion $officeCountry } } } catch { # 你原有自定义错误处理逻辑 write-host("$(Get-TimeStamp) *****ERROR*****: ERROR ATTEMPTING TO CREATE NEW CONTACT RECORD: $($displayName) . CHECK ERROR BELOW") write-host($_.Exception|format-list -force) write-host("$(Get-TimeStamp) Adding user to error ticket list") $errMsg = $error[0].ToString() + $error[0].InvocationInfo.PositionMessage $errMsg -replace ',','|' } finally { # 恢复原有错误处理配置 $ErrorActionPreference = $originalErrorAction }
修改后再次运行,当Set-Contact出现参数错误、执行错误时就会直接进入catch块执行你的自定义错误逻辑。
内容的提问来源于stack exchange,提问作者Daniel Favreau
相关产品推荐
相关产品推荐

