2017-01-09 106 views
1

我有一个奇怪的问题,即时通讯使用try/catch方法的一些cmdlet其工作的一些不。在PowerShell中捕获错误

你能提供意见吗?

这一个是工作的罚款:

try 
{ 
$LookingForRemoteMailboxOnPrem = Get-RemoteMailbox $info -ErrorAction Stop | select -ExpandProperty UserPrincipalName 
} 
catch 
{ 
string]$t = $Error[0] 
} 

但是这个人是不是:变量t

+2

未处理的错误是什么?如果你设置了'$ ErrorActionPreference ='Stop'',你会得到同样的行为吗? –

+0

尝试'$ t = $ _'而不是 –

+0

@AnsgarWiechers $ ErrorActionPreference设置为继续 – user3574248

回答

0

$ErrorActionPreference

try 
{ 
$EnableRemoteMailbox = Enable-RemoteMailbox $info -RemoteRoutingAddress $remote -PrimarySmtpAddress $info2 -ErrorAction Stop 
} 
catch 
{ 
[string]$t = $Error[0] 
} 

不保存错误$默认情况下设置为Continue。这意味着如果PowerShell可以从错误中“恢复”,它不会抛出异常。您可以使用-ErrorAction参数更改每个cmdlet的行为。

link给出了一个很好的例子:

Try {dir c:\missingFolder} Catch [System.Exception] {"Caught the exception"} Finally {$error.Clear() ; "errors cleared"}

字符串"Caught the exception不PowerShell的窗口出现。如果您将-ErrorAction设置为Stop,则会引发异常。

详细描述here