Powershell陷阱[Exception]没有捕获我的错误

Den*_*nis 7 powershell exception-handling exception powershell-trap

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

我将不胜感激如何解决这个问题的任何提示或指示.

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

trap [Exception] {
Run Code Online (Sandbox Code Playgroud)

但那也不起作用.

这是脚本:

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."
Run Code Online (Sandbox Code Playgroud)

输出:

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 >
Run Code Online (Sandbox Code Playgroud)

man*_*lds 6

试试这样:

trap { write-host "file not found, skipping";continue;}
$modtime = Get-ItemProperty c:\manoj -erroraction stop
Run Code Online (Sandbox Code Playgroud)

根据OP的评论:

我想你误解了你所链接的文章中的内容:

在这个例子中,我们使用继续导致执行返回陷阱所在的范围并执行下一个命令.重要的是要注意执行只返回陷阱的范围,所以如果异常被抛出到函数内部,甚至在if语句中,并且被困在它之外......继续将在嵌套范围的末尾拾取.

所以如果你做这样的事情:

trap{ write-host $_; continue;}
throw "blah"
write-host after
Run Code Online (Sandbox Code Playgroud)

after 将被打印.

但如果你做这样的事情:

trap{ write-host $_ ; continue}
function fun($f) {


      throw "blah"
      write-host after
}

fun
write-host "outside after"
Run Code Online (Sandbox Code Playgroud)

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".
      }
Run Code Online (Sandbox Code Playgroud)