Assets/Get-OpsJobHistory.ps1

<#
.SYNOPSIS
    Gets the history of Ops Jobs based on JSON logs.
.PARAMETER JobName
    Optional specific job name.
.PARAMETER Count
    Number of recent entries to check.
#>

param (
  [string]$JobName = "*",
  [int]$Count = 10
)

$LogDir = "C:\Ops\Logs"
# Look for JSON history files
$Pattern = "$JobName.history.json"

$Files = Get-ChildItem -Path $LogDir -Filter $Pattern

$Results = @()

foreach ($File in $Files) {
  # Read the JSON lines, parse them, sort by timestamp descending
  $Entries = Get-Content -Path $File.FullName | ConvertFrom-Json
    
  # If multiple entries, ConvertFrom-Json returns array. If single, object. Ensure array.
  if ($Entries -isnot [System.Array]) {
    $Entries = @($Entries)
  }

  # Filter for start/end events to construct history
  # For simplicity, we'll just show the last N log entries that are ERROR or INFO "Job completed"
    
  $RelevantEntries = $Entries | Where-Object { 
    $_.Message -match "Job completed successfully" -or $_.Level -eq "ERROR" 
  } | Sort-Object Timestamp -Descending | Select-Object -First $Count

  foreach ($Entry in $RelevantEntries) {
    $Status = "Unknown"
    if ($Entry.Level -eq "ERROR") { $Status = "Failed" }
    elseif ($Entry.Message -match "Job completed successfully") { $Status = "Success" }

    $Results += [PSCustomObject]@{
      JobName   = $File.BaseName -replace ".history", ""
      Timestamp = $Entry.Timestamp
      Status    = $Status
      Message   = $Entry.Message
    }
  }
}

return $Results | Sort-Object Timestamp -Descending | Select-Object -First $Count