Powershell 陷阱 [异常] 没有捕捉到我的错误

标签 powershell exception exception-handling powershell-trap

出于某种原因,当我针对不存在的文件运行以下脚本时,我的脚本没有捕获异常。我基于我在网上找到的示例中的代码,但它似乎对我不起作用。

我将不胜感激有关如何解决此问题的任何提示或指示。

注意:在下面的例子中我也试过

trap [Exception] {

但这也不起作用。

这是脚本:
function CheckFile($f) {

      trap {
        write-host "file not found, skipping".
        continue
      }

      $modtime = (Get-ItemProperty $f).LastWriteTime

      write-host "if file not found then shouldn't see this"
}


write-host "checking a file that does not exist"
CheckFile("C:\NotAFile")
write-host "done."

输出:
PS > .\testexception.ps1
checking a file that does not exist
Get-ItemProperty : Cannot find path 'C:\NotAFile' because it does not exist.
At C:\Users\dleclair\Documents\Visual Studio 2010\lib\testexception.ps1:12 char:35
+       $modtime = (Get-ItemProperty <<<<  $f).LastWriteTime
    + CategoryInfo          : ObjectNotFound: (C:\NotAFile:String) [Get-ItemProperty], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand

if file not found then shouldn't see this
done.
PS >

最佳答案

像这样尝试:

trap { write-host "file not found, skipping";continue;}
$modtime = Get-ItemProperty c:\manoj -erroraction stop

根据 OP 的评论:

我认为您误解了您链接到的文章中所说的内容:

In this example, we used continue to caused execution to return to the scope the trap is in and execute the next command. It’s important to note that execution only returns to the scope of the trap, so if the exception was thrown inside a function, or even inside a if statement, and trapped outside of it … the continue will pick up at the end of the nested scope.



所以如果你做这样的事情:
trap{ write-host $_; continue;}
throw "blah"
write-host after
after将被打印。

但是如果你做这样的事情:
trap{ write-host $_ ; continue}
function fun($f) {


      throw "blah"
      write-host after
}

fun
write-host "outside after"
after不会被打印,但 outside after将会。

或者,使用 try-catch 块:
      try{
      $modtime = (Get-ItemProperty $f -erroraction stop).LastWriteTime
      write-host "if file not found then shouldn't see this"
      }
      catch{
        write-host "file not found, skipping".
      }

关于Powershell 陷阱 [异常] 没有捕捉到我的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7199357/

相关文章:

powershell - 如何将命令数组传递给 dotnet cli 应用程序

java - 将 Java 应用程序的新异常通知管理员的最佳方式是什么?

c# - 在任务异常的情况下,根据用户输入多次重试任务

python-3.x - 即使在任何时候都不访问e,都将异常定义为变量(作为e除外的异常)的最佳实践吗?

c# - 字符串缺少终止符 : "

Flutter:使用 Navigator.of(context).pop() 时出现异常;

c# - 找不到适合指定文化或中性文化的任何资源

c# - 从 x64 C# 应用程序调用 x86 PowerShell 脚本

powershell - PowerShell 的 Get-ChildItem cmdlet 返回的可能的 'Mode' 值是什么?

.net - 使用 PowerShell 远程处理在事件用户 session 中启动程序