0

I would like to have a PowerShell Script to check the task scheduler. If the task name exists then delete it.

if (schtasks /query  /tn "mytask") {
    schtasks /delete /tn "mytask" /f | Out-Null
}

The syntax works well when the user has the task name in the task scheduler. However, the PowerShell returns the error message when the task name doesn't exist:

schtasks : ERROR: The system cannot find the file specified.
At line:1 char:5
+ if (schtasks /query  /tn "mytask") {
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (ERROR: The syst...file specified.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Is there any way to avoid or hide the PS return the error message?

1 Answer 1

2

You can use the stream redirection operator > to supress errors from schtasks:

if(schtasks /query  /tn "mytask" 2>$null){
    schtasks /delete /tn "mytask" /f | Out-Null
}

But I would personally prefer using Get-ScheduledTask from the ScheduledTasks module, then use the -ErrorAction common parameter to ignore any errors:

if(Get-ScheduledTask -TaskName "mytask" -ErrorAction Ignore){
    Unregister-ScheduledTask -TaskName "mytask" -Confirm:$false | Out-Null
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.