PowerShell try-catch 不起作用 [英] PowerShell try-catch isn't working
本文介绍了PowerShell try-catch 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写脚本并想检查任务名称是否存在.到目前为止看起来像这样:
I'm working on a script and want to check, if a taskname is existing. It looks so far like this:
try {
Get-ScheduledTaskInfo -TaskName "taskname"
}
catch {
echo "doesn't exist"
}
当我运行代码时,它会向我打印错误消息而不是不存在":
When I run the code, it prints me the error message and not "doesn't exist":
PS C:\Windows\system32> try {
Get-ScheduledTaskInfo -TaskName "taskname"
}
catch {
echo "doesn't exist"
}
Get-ScheduledTaskInfo : The system cannot find the file specified.
At line:2 char:5
+ Get-ScheduledTaskInfo -TaskName "taskname"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Get-ScheduledTaskInfo], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070002,Get-ScheduledTaskInfo
有人知道为什么没有触发标语吗?
Does anybody has an idea why the catch phrase is not triggered?
感谢您的帮助!
最好的问候
推荐答案
try
/catch
only catches terminating errors:
使用 Try、Catch 和 finally 块来响应或处理脚本中的终止错误
Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts
使用 -ErrorAction Stop
将您的非终止错误转变为终止错误:
Use -ErrorAction Stop
to turn your non-terminating error into a terminating error:
Get-ScheduledTaskInfo -TaskName "taskname" -ErrorAction Stop
这篇关于PowerShell try-catch 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文