如何在PowerShell中捕获异常?

5
如果我的代码抛出异常,我会收到一个错误消息,但我不知道如何正确地捕获(或确定)被抛出的异常。通常我只会捕获 System.Exception,这是一个坏主意。
以下是一个例子... 我试图在不存在的驱动器上创建文件夹:
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 异常,但是重新运行我的脚本仍然会产生未捕获的异常。

有没有有效处理任何类型异常的提示?

1个回答

5

运行该命令后,请查看$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 Stop将非终止错误转换为终止错误,以便它生成一个你可以捕获的异常,例如:
PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname}
System.Management.Automation.DriveNotFoundException

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接