【问题标题】:Task Scheduler - get history information into script variables任务计划程序 - 将历史信息获取到脚本变量中
【发布时间】:2018-03-09 04:26:53
【问题描述】:

有没有办法将任务调度程序历史信息放入批处理或 PowerShell 脚本中的数组或变量中。

例如,获取任务名称、任务开始时间(事件 ID:100)和完成时间(事件 ID:102)等信息。 这样我就可以使用这些信息更新 SQL 数据库。 (sql表可能是这样的,我知道一旦我得到信息如何插入数据库)

TaskName    TaskStart              TaskCompleted
task1       27/09/2017 09:00:00    27/09/2017 10:00:00    
task2       27/09/2017 12:00:00    27/09/2017 16:00:00    
task1       04/10/2017 09:00:00    04/09/2017 09:55:00    

基本上我不知道如何检索这些信息,如果可能的话。 谢谢

【问题讨论】:

  • 你有没有考虑使用:SCHTASKS /Query /V
  • 你有什么版本的 PowerShell?你打算从什么操作系统运行它?你有什么尝试,因为这看起来像是一个不符合 SO 精神的代码请求?
  • 我可能只会使用schtasks /query /v /fo csv | ConvertFrom-Csv

标签: powershell batch-file taskscheduler


【解决方案1】:

任务计划程序记录到以下事件通道:
Microsoft-Windows-TaskScheduler/Operational

您可以使用Get-WinEvent 收集事件。首先为 id 100 开始事件定义一个过滤器哈希表

# Event filter for the initial query for all "Start" events in the last 24 hours
$EventFilter = @{
    LogName = 'Microsoft-Windows-TaskScheduler/Operational'
    Id = 100
    StartTime = [datetime]::Now.AddDays(-1)
}

我们需要从开始事件中提取一些属性值,以便找到相关的完成事件,所以让我们创建一个属性选择器

# PropertySelector for the Correlation id (the InstanceId) and task name
[string[]]$PropertyQueries = @(
    'Event/EventData/Data[@Name="InstanceId"]'
    'Event/EventData/Data[@Name="TaskName"]'
)
$PropertySelector = New-Object System.Diagnostics.Eventing.Reader.EventLogPropertySelector @(,$PropertyQueries)

现在检索开始事件,找到对应的完成事件,并将信息作为新的自定义对象输出:

# Loop through the start events
$TaskInvocations = foreach($StartEvent in Get-WinEvent -FilterHashtable $EventFilter){
    # Grab the InstanceId and Task Name from the start event
    $InstanceId,$TaskName = $StartEvent.GetPropertyValues($PropertySelector)

    # Create custom object with the name and start event, query end event by InstanceId
    [pscustomobject]@{
        TaskName = $TaskName
        StartTime = $StartEvent.TimeCreated
        EndTime = $(Get-WinEvent -FilterXPath "*[System[(EventID=102)] and EventData[Data[@Name=""InstanceId""] and Data=""{$InstanceId}""]]" -LogName 'Microsoft-Windows-TaskScheduler/Operational' -ErrorAction SilentlyContinue).TimeCreated
    }
}

您可以使用$TaskInvocations 中的对象填充DataTable,或根据属性值生成插入查询

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2017-04-19
    • 2012-06-16
    • 2023-02-07
    相关资源
    最近更新 更多