2013-10-01 47 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

非常感谢你! –