PowerShell try-catch isn't working

痴心易碎 提交于 2019-12-24 09:28:25

问题


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?

Thanks for any help!

Best regards


回答1:


try/catch only catches terminating errors:

Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts

Use -ErrorAction Stop to turn your non-terminating error into a terminating error:

Get-ScheduledTaskInfo -TaskName "taskname" -ErrorAction Stop



回答2:


You can set global variable parameter $ErrorActionPreference to stop (détail : here). Not necessary to put -Erroraction on all commands with this method ;)

$ErrorActionPreference= "Stop"

try {
    Get-ScheduledTaskInfo -TaskName "taskname"
}
catch {
    echo "doesn't exist"
}


来源:https://stackoverflow.com/questions/48707150/powershell-try-catch-isnt-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!