2013-10-01 46 views
4

如果我有一段引發異常的代碼,我會收到一條錯誤消息,但不知道如何正確捕獲(或確定)正在引發的異常。通常我會抓住System.Exception這是一個壞主意。如何在PowerShell中捕獲異常?

下面是一個例子...我試圖創建一個驅動器上的文件夾不存在:

PS <dir> .\myScript.ps1 z:\test 
mkdir : Cannot find drive. A drive with the name 'z' does not exist. 
At <dir>myScript.ps1:218 char:7 
+  mkdir $args[0] 1> $null 
+  ~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (z:String) [New-Item], DriveNotFoundExc 
    eption 
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemComm 
    and 

我試着追趕System.DriveNotFoundException但重新運行腳本還是產生未捕獲的異常。

是否有任何提示可以有效處理任何類型的異常?

回答

4

運行該命令後,檢查$ error [0]的內容。查看例外屬性例如:

$error[0] | fl * -force 

writeErrorStream  : True 
PSMessageDetails  : 
Exception    : System.Management.Automation.DriveNotFoundException: Cannot find drive. A drive with the name 
         'z' does not exist. 
          at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean 
         automount) 
          at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean 

該特殊例外將是[System.Management.Automation.DriveNotFoundException]

順便說一句,如果你想「趕」是例外,您需要將非終止錯誤轉換成使用-EA停止終止錯誤,以便它生成異常,你可以趕上如:

PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname} 
System.Management.Automation.DriveNotFoundException 
+0

非常感謝你! –