为什么从PowerShell作为脚本运行以下代码中的try / catch语句不起作用?如果我在运行脚本之前将$ ErrorActionPreference设置为'Stop',则按预期运行,但是如果将其设置为'Continue',则好像脚本中的$ ErrorActionPreference ='Stop'行无效。我输入了两个DC都不存在的用户的姓氏和名字。
$UserCredential = Get-Credential -Credential
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -
ConnectionUri 'serveromitted' -Authentication Kerberos -Credential
$UserCredential
$dcs = 'dc1','dc2'
$ErrorCount = 0
$firstname = Read-Host -Prompt 'Enter First Name'
$lastname = Read-Host -Prompt 'Enter Last Name'
$alias = $firstname.substring(0,1).tolower()+$lastname.tolower()
$primarysmtpaddress = $alias+'@domain.com'
import-pssession $ExchangeSession
$ErrorActionPreference = 'Stop'
foreach ($dc in $dcs)
{
try {
Get-Recipient -DomainController $dc -Identity $PrimarySmtpAddress -erroraction stop
}
catch {
$MailboxError = $_.Exception.Message
$MailboxErrorRegex = "^The operation couldn't be performed because object '.*' couldn't be found on '.*'\.$"
if ($MailboxError -match $MailboxErrorRegex)
{
$ErrorCount++
}
}
$ErrorCount
}
在此先感谢您的帮助。