任务计划程序-将历史记录信息转换为脚本变量

Sup*_*Sup 7 powershell batch-file taskscheduler

有没有一种方法可以将任务计划程序的历史记录信息放入批处理或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    
Run Code Online (Sandbox Code Playgroud)

基本上,即使可能,我也不知道如何检索该信息。谢谢

Mat*_*sen 6

任务计划程序将记录到以下事件通道:
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)
}
Run Code Online (Sandbox Code Playgroud)

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

# 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)
Run Code Online (Sandbox Code Playgroud)

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

# 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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