简体   繁体   中英

Hide or avoid the PowerShell Script return the error message

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?

I am very new to PowerShell, any help is appreciated!

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM