windows - 如何在 PowerShell 中捕获异常?

标签 windows exception powershell

如果我有一段抛出异常的代码,我会收到一条错误消息,但我不知道如何正确捕获(或确定)抛出的异常。通常我只会捕获 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

我已经 try catch System.DriveNotFoundException,但重新运行我的脚本仍然会产生未捕获的异常。

是否有任何关于有效处理任何类型异常的提示?

最佳答案

运行命令后立即检查 $error[0] 的内容。查看 Exception 属性,例如:

$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

关于windows - 如何在 PowerShell 中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19118126/

相关文章:

与 Windows 相比,Python 请求在 Linux 中需要更长的时间才能返回

.net - Windows XP、Vista 和 7 上安装了哪个版本的 .NET 框架?

c++ - C++读取访问冲突,结构 vector

c# - 在测试中抛出新的异常

json - ConvertFrom-Json 返回 "Cannot process argument because the value of argument "名称“无效”。

powershell - Send-MailMessage 多个收件人

windows - 处理远程电脑的命令

java - 如何处理参数中的空格?

java - 使用三元运算符抛出已检查或未检查的异常

python - 使用 Tee-Object 将 python 脚本的结果输出到终端和文件