标签: powershell-trap

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

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

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

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

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

powershell exception-handling exception powershell-trap

7
推荐指数
1
解决办法
1万
查看次数

Powershell陷阱不会被持续触发

我无法理解为什么我在Powershell中看到这种行为:

PS C:\> trap { "Got it!" } 1/0
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/0 <<<<

PS C:\> trap { "Got it!" } 1/$null
Got it!
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/$ <<<< null
Run Code Online (Sandbox Code Playgroud)

为什么一个表达式会触发陷阱而另一个表达式不会?

error-handling powershell powershell-trap

3
推荐指数
1
解决办法
789
查看次数