【问题标题】:Script to search for specific task in scheduler and delete this task在调度程序中搜索特定任务并删除此任务的脚本
【发布时间】:2021-05-19 01:30:10
【问题描述】:

我在这个领域很新,我有点迷茫,但是当我查看:https://serverfault.com/questions/604673/how-to-print-out-information-about-task-scheduler-in-powershell-script 时,这部分回答了我的问题。我正在寻找允许我搜索现有任务并删除他的脚本。问题出在 Powershell 版本中。在我的修订版中 Get-ShceduledTask 不存在,我必须寻找解决方案如何使用此 cmdlet 进行搜索。我还必须注意,我无法将 Powershell 更改或升级到更好的版本。

所以,总而言之,下面的代码在某些时候可以工作,但如果有一些可以帮助我弄清楚如何完成这个?

$sched = New-Object -Com "Schedule.Service"
$sched.Connect()
$out = @()
$sched.GetFolder("\").GetTasks(0) | % {
    $xml = [xml]$_.xml
    $out += New-Object psobject -Property @{
        "Name" = $_.Name
        "Status" = switch($_.State) {0 {"Unknown"} 1 {"Disabled"} 2 {"Queued"} 3 {"Ready"} 4 {"Running"}}
        "NextRunTime" = $_.NextRunTime
        "LastRunTime" = $_.LastRunTime
        "LastRunResult" = $_.LastTaskResult
        "Author" = $xml.Task.Principals.Principal.UserId
        "Created" = $xml.Task.RegistrationInfo.Date
    }
}

$out | fl Name,Status,NextRuNTime,LastRunTime,LastRunResult,Author,Created

【问题讨论】:

  • 究竟是什么不起作用?
  • 您运行的是哪个版本的 Powershell?也没有真正的理由使用 COM。只需将 Windows 可执行文件用于计划任务:schtasks.exe /?

标签: powershell scheduled-tasks


【解决方案1】:

继续我的评论。

它们只是您文件系统上的文件。

Task Scheduler 1.0 API 使用...

Get-ChildItem -Path 'C:\Windows\Tasks'

...用于创建和枚举任务的文件夹。

Task Scheduler 2.0 API 使用...

Get-ChildItem -Path 'C:\Windows\System32\Tasks' 

...创建和枚举任务。

以及在注册表中:

Get-ChildItem -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks'
Get-ChildItem -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree'

当然,使用 Powershell(您系统上的版本或您可以通过 PSRemoting 从另一个系统代理到您的系统的版本)您只需将任务名称传递给 cmdlet。当然,根据需要进行过滤,并在确定您拥有所需的内容时删除 -WhatIf。

Get-ScheduledTask | 
ForEach-Object {Unregister-ScheduledTask -TaskName $PSItem.TaskName -WhatIf}

这是我个人 ModuleLibrary 中的一个函数。

Function Get-ScheduledTasks
{
    [CmdletBinding(SupportsShouldProcess)]
    [Alias('gst')]

    Param
    (
    
    )

    schtasks.exe /query /v /fo csv | 
    ConvertFrom-Csv | 
    Where-Object { $PSItem.TaskName -ne 'TaskName' } | 
    Sort-Object TaskName | 
    Out-GridView -Title 'All scheduled tasks' -PassThru
}

从 Out-GridView 中选择将使该选择可用于其他操作。

您可以轻松地创建一个新函数来删除它们或在上面的函数中添加一个开关参数;添加此命令:

schtasks.exe /delete /tn "MyTasks/Task1" /f

【讨论】:

  • 很遗憾 Get-ScheduledTask cmdlet 不存在,我只能看到 Get-ScheduledJob。
  • 我知道您使用的是 PowerShell 版本。您确实已经在原始帖子中声明了这一点。这就是为什么我发布了自定义功能供您使用。它不能替代本机 PowerShell cmdlet。这是一种解决方法,您可以在具有您喜欢使用的 cmdlet 的 PowerShell 版本上获得。
  • 我实际上可以通过 Powershell 设置 cmd 是否 xml 文件存在于 C:\Windows\System32\Tasks 中,如果存在则跳过创建任务,否则创建任务
  • 无论如何感谢您的回答,它会引导我做出一些选择
  • 不用担心。我们尽我们所能。
猜你喜欢
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 2011-09-28
  • 2016-07-15
  • 1970-01-01
  • 2023-04-05
  • 2019-03-10
  • 2013-02-18
相关资源
最近更新 更多