You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PowerShell脚本以导出含触发与完成记录的计划任务历史数据?

导出包含触发/完成历史的计划任务到CSV

原来的schtasks /query只能导出任务的基本配置信息,拿不到历史执行记录。要加入你需要的「Task Triggered on Scheduler」(事件ID 106)和「Task Completed」(事件ID 102)记录,得结合PowerShell的计划任务模块和事件日志查询来实现,以下是完整脚本:

$outputDirectory = "\\COM\Data\MI\MI\Download\Supporting Files\Data"
$outputFile = Join-Path -Path $outputDirectory -ChildPath "$env:USERNAME.csv"

# 确保输出目录存在
if (-not (Test-Path -Path $outputDirectory)) {
    New-Item -ItemType Directory -Path $outputDirectory | Out-Null
}

# 获取所有本地计划任务(如需远程可添加 -CimSession 参数)
$scheduledTasks = Get-ScheduledTask | Select-Object TaskName, TaskPath, State, Author, Description, InstanceId

# 初始化结果数组
$exportData = @()

foreach ($task in $scheduledTasks) {
    # 查询当前任务的触发和完成事件
    $eventFilter = @"
*[System[Provider[@Name='Microsoft-Windows-TaskScheduler'] and (EventID=106 or EventID=102) and Correlation[@ActivityID='$($task.InstanceId)']]]
"@
    try {
        $taskEvents = Get-WinEvent -LogName "Microsoft-Windows-TaskScheduler/Operational" -FilterXPath $eventFilter -ErrorAction Stop
    }
    catch {
        # 没有历史记录的任务,生成空记录
        $taskEvents = $null
    }

    if ($taskEvents) {
        foreach ($event in $taskEvents) {
            # 根据事件ID匹配描述
            $eventDesc = switch ($event.Id) {
                106 { "Task Triggered on Scheduler" }
                102 { "Task Completed" }
                default { $event.Message }
            }

            # 合并任务信息和事件记录
            $exportItem = [PSCustomObject]@{
                TaskName        = $task.TaskName
                TaskPath        = $task.TaskPath
                State           = $task.State
                Author          = $task.Author
                Description     = $task.Description
                EventTime       = $event.TimeCreated
                EventType       = $eventDesc
            }
            $exportData += $exportItem
        }
    }
    else {
        # 无历史记录的任务,仅导出基本信息
        $exportItem = [PSCustomObject]@{
            TaskName        = $task.TaskName
            TaskPath        = $task.TaskPath
            State           = $task.State
            Author          = $task.Author
            Description     = $task.Description
            EventTime       = $null
            EventType       = "No historical records"
        }
        $exportData += $exportItem
    }
}

# 导出到CSV
$exportData | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8

Write-Host "任务已导出到: $outputFile"

关键说明:

  • 用Get-ScheduledTask获取任务的基本配置(包括InstanceId,用来关联事件日志)
  • 通过Get-WinEvent查询「Microsoft-Windows-TaskScheduler/Operational」日志,用XPath过滤指定事件ID
  • 每个任务的历史记录会单独生成一行,无历史的任务也会保留基本信息
  • 导出的CSV用UTF8编码,避免中文乱码

内容的提问来源于stack exchange,提问作者Gaus Shaikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:53:25