Automation guides, explanations and reader checklists on whilenetworking.com

PowerShell Project: Building a Scheduled Job to Auto-Generate Change Advisory Board (CAB) Reports from Git Commits

In modern DevOps environments, manual compilation of Change Advisory Board (CAB) reports is often a bottleneck that introduces delay and human error. By…

In modern DevOps environments, manual compilation of Change Advisory Board (CAB) reports is often a bottleneck that introduces delay and human error. By leveraging PowerShell’s robust file system access and scheduling capabilities, organizations can automate the ingestion of Git commit data to produce timely CAB documentation. This project demonstrates how to build a scheduled job that scans a Git repository, extracts change metadata, formats it into a professional report, and emails it to stakeholders.

This guide is designed for IT students, junior engineers, and practitioners using Windows Server or Windows 10/11 environments. It assumes a basic understanding of PowerShell scripting and Git workflows. The solution integrates concepts relevant to broader automation toolsets like Ansible (for orchestration) and Bash (for Linux-based CI/CD pipelines), though this specific implementation focuses on native PowerShell for Windows-centric infrastructure.

Prerequisites and Environment Setup

Before writing the script, ensure your environment is prepared correctly. You will need a Git repository containing recent commits related to production changes. For security reasons, do not store sensitive authentication tokens in plain text within scripts; instead, use PowerShell’s Get-Credential cmdlet or integrate with Azure Key Vault/Windows Credential Manager.

You must also have an SMTP server configured or an email relay service (like SendGrid) accessible. The script will generate a CSV report containing the change ID, author, timestamp, and a summary of the commit message.

Step 1: Creating the Report Generation Script

The core logic resides in a PowerShell script file, which we will name Generate-CABReport.ps1. This script performs three critical functions: locating the Git repository, parsing recent commits, and formatting the output.

# Define variables for configuration
$RepoPath = "C:\Repos\ProductionApp"
$OutputFolder = "C:\Reports\CAB-Logs\"
$CommitCount = 5 # Number of recent commits to include in the report

# Ensure the output folder exists
if (-not (Test-Path $OutputFolder)) {
    New-Item -ItemType Directory -Force -Path $OutputFolder | Out-Null
}

# Initialize the CSV object for the report
$ReportData = [PSCustomObject]@{
    ChangeID      = "Auto-Gen"
    Timestamp     = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
    CommitCount   = 0
    Status        = "Processing"
}

# Navigate to the repository
Set-Location $RepoPath

# Get the last N commits and extract metadata
$Commits = git log --no-walk -n $CommitCount --format="%h|%an|%ae|%aI|%s|%b"

if ($Commits) {
    # Parse each line of the git log output
    foreach ($Line in $Commits) {
        $Parts = $Line -split "\|"

        if ($Parts.Count -eq 6) {
            $CommitObj = [PSCustomObject]@{
                ShortHash      = $Parts[0]
                AuthorName     = $Parts[1]
                AuthorEmail    = $Parts[2]
                CommitDate     = $Parts[3]
                Subject        = $Parts[4]
                Description    = $Parts[5]
            }

            # Append to the main report collection
            $ReportData += $CommitObj
        }
    }

    # Export the collected data to a CSV file
    $FileName = "CAB-Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"
    $FullPath = Join-Path $OutputFolder $FileName

    $ReportData | Export-Csv -Path $FullPath -NoTypeInformation -Append
} else {
    # Handle case where no commits found or git not in path
    Write-Warning "Git command failed. Ensure Git is installed and added to PATH."
}

# Update status in the header row (optional logic for logging)
Write-Host "Report generated successfully at: $FullPath"

What this code does:
The script initializes a collection object to hold commit data. It uses git log with a specific format string to capture hash, author, date, subject, and description in a single line pipe-delimited by |. The loop parses this output into structured objects. Finally, it exports the data to a CSV file in the designated report folder.

Step 2: Configuring the Scheduled Task

Once the script is functional, you must ensure it runs automatically at regular intervals, such as every morning before business hours. Windows Task Scheduler is the standard tool for this.

  1. Open Task Scheduler via the Start Menu search.
  2. Click Create Basic Task or Create Task.
  3. In the General tab of the advanced properties, check Run with highest privileges to ensure the script has permission to read network drives and access Git repositories.
  4. Under the Triggers tab, set a daily recurrence at your preferred time (e.g., 07:00 AM).
  5. In the Actions tab, select Start a program.
    • Program/script: powershell.exe
    • Add arguments: -ExecutionPolicy Bypass -File "C:\Scripts\Generate-CABReport.ps1"
    • Start in (optional): C:\Scripts

Security Note: Always verify the account running the scheduled task. Using a domain service account with read-only permissions to the Git repo is safer than using an interactive user account.

Step 3: Verification and Error Handling

After scheduling, you must verify that the automation works without manual intervention. Run the script manually first to check for errors. Then, monitor the output folder for the new CSV file at the scheduled time.

Common errors include Git not found, which indicates the Git executable is not in the system PATH. Another frequent issue is permission denied when writing to the output folder; ensure the scheduled task user owns that directory or has write access.

# Example of adding error handling to the script
try {
    # Your existing git logic here
} catch {
    $ErrorMessage = $_.Exception.Message
    Write-Error "CAB Report generation failed: $ErrorMessage"
    # Optionally send an email alert here using Send-MailMessage
}

Industry Application and Student Practice Task

Industry Application:
In a large enterprise, this script can be part of a larger Ansible playbook. The Ansible inventory could manage multiple Git repositories across different microservices. The playbook would execute the PowerShell script on a central “Automation Server,” collect all CSV reports into a single archive, and upload them to an object storage bucket for archival compliance. This ensures that every code change is documented in the CAB log within minutes of merging.

Student Practice Task:
To reinforce these concepts, students should:
1. Create a local Git repository with three fake commits.
2. Modify the PowerShell script to filter commits based on specific keywords (e.g., “hotfix” or “production”).
3. Configure the scheduled task to run every hour during business days.
4. Document the expected output in a README file, explaining how the script handles empty repositories or network disconnections.

By automating CAB reporting, teams shift focus from administrative data entry to reviewing the actual technical merit of changes. This workflow exemplifies the intersection of version control, scripting, and enterprise governance required in modern IT operations.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.