【问题标题】:Is there a possibility to query all scheduled tasks returning any job with Last Run Result not (0x0) using powershell?是否有可能使用powershell查询所有返回最后运行结果不是(0x0)的作业的计划任务?
【发布时间】:2019-09-21 17:26:15
【问题描述】:

我们(我们的公司)正在服务器上运行多个计划任务。最近一些任务开始运行失败。我们想使用 powershell 查询所有报告上次运行结果不是 0x0 的任何人的计划作业。

我已经尝试了很多研究以找到一种简单的方法,但只找到了可以按名称查询计划任务(仅检查一个任务)但不能按上次运行结果查询的脚本。为每个新安装的计划任务添加新代码行不会有帮助。

关于该主题有一个非常相似的条目,但如上所述,任务名称作为参数。 (How to send email when SPECIFIC scheduled task fails to run)

$ScheduledTaskName = "Taskname"
$Result = (schtasks /query /FO LIST /V /TN $ScheduledTaskName  | findstr "Result")
$Result = $Result.substring(12)
$Code = $Result.trim()

If ($Code -gt 0) {
    $User = "admin@company.com"
    $Pass = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force
    $Cred = New-Object System.Management.Automation.PSCredential $User, $Pass


$From = "Alert Scheduled Task <task@servername>"
$To = "Admin <admin@company.com>"
$Subject = "Scheduled task 'Taskname' failed on SRV-001"
$Body = "Error code: $Code"
$SMTPServer = "smtp.company.com"
$SMTPPort = "25"

Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $Cred
}

我猜代码应该是这样的

Get-ScheduledTask | where LastTaskResult -NE "0x0"

【问题讨论】:

    标签: powershell scheduled-tasks


    【解决方案1】:

    使用Get-ScheduledTaskInfo

    Get-ScheduledTask -TaskPath "\" | Where State -ne "Disabled" | Get-ScheduledTaskInfo | Where LastTaskResult -ne 0
    

    在我的示例中,我只是假设您想要任务根目录中的任务,而不是 MS 子文件夹中的任何任务。如果您在子文件夹中存储或关心任务,那么显然修改任务路径或以其他方式识别您想要的任务。

    Get-ScheduledTaskInfo 返回一堆您可以搜索/选择的属性。不包括 Cim (WMI) 属性,它们是:

    TaskName,TaskPath,LastRunTime,LastTaskResult,NextRunTime,NumberofMissedRuns
    

    【讨论】:

      猜你喜欢
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多