Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell try-catch isn't working

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

like image 657
Paul Avatar asked May 11 '26 22:05

Paul


1 Answers

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
like image 150
G42 Avatar answered May 16 '26 06:05

G42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!