2017-01-09 124 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