【发布时间】:2011-08-26 02:11:47
【问题描述】:
由于某种原因,当我对不存在的文件运行以下脚本时,我的脚本没有捕获异常。我基于我在网上找到的示例中的代码,但它似乎对我不起作用。
如果有任何关于如何解决此问题的提示或指示,我将不胜感激。
注意:在下面的示例中我也尝试过
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 >
【问题讨论】:
标签: powershell exception exception-handling powershell-trap