[英]Hide or avoid the PowerShell Script return the error message
I would like to have a PowerShell Script to check the task scheduler.我想要一个 PowerShell 脚本来检查任务调度程序。 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:但是,当任务名称不存在时,PowerShell 会返回错误消息:
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?有什么办法可以避免或隐藏 PS 返回的错误信息?
I am very new to PowerShell, any help is appreciated!我对 PowerShell 非常陌生,感谢您的帮助!
You can use the stream redirection operator >
to supress errors from schtasks
:您可以使用 stream 重定向运算符>
来抑制来自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:但我个人更喜欢使用ScheduledTasks
模块中的Get-ScheduledTask
,然后使用-ErrorAction
通用参数来忽略任何错误:
if(Get-ScheduledTask -TaskName "mytask" -ErrorAction Ignore){
Unregister-ScheduledTask -TaskName "mytask" -Confirm:$false | Out-Null
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.