gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:29:39 31 4
gpt4 key购买 nike

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

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

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

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com