Automation guides, explanations and reader checklists on whilenetworking.com

PowerShell Deep Dive: Constructing a Function to Parse NPM Event Logs and Trigger Alerts for CPU Spikes

In modern server environments, the Windows Performance Monitor (NPM) generates a continuous stream of events. While many of these are informational, sudden…

In modern server environments, the Windows Performance Monitor (NPM) generates a continuous stream of events. While many of these are informational, sudden spikes in processor usage can indicate resource exhaustion, runaway processes, or potential security breaches like cryptomining. Manually reviewing these logs is inefficient and prone to human error. This guide demonstrates how to construct a robust PowerShell function that automates the parsing of NPM Event Logs to detect CPU threshold violations and triggers immediate alerts. This approach leverages Windows-native capabilities to build a reliable monitoring workflow without requiring external agents or complex licensing.

Understanding the Architecture and Prerequisites

Before writing code, it is essential to understand the components involved. The script will rely on the WinEvent class within PowerShell’s .NET framework to access the EventLog. Specifically, we are targeting the “System” log, where the Performance Counter service (often associated with PerfMon) writes critical warnings.

Prerequisites:
* Operating System: Windows Server 2016+ or Windows 10/11 Pro/Enterprise.
* PowerShell Version: PowerShell 5.1 or PowerShell 7+. This guide assumes a standard Windows environment with PowerShell 5.1, as it is the default on most enterprise servers.
* Permissions: The script must run under an account with Local Security Policy permissions to read system logs (typically Administrators).
* Safety Note: Always test automation scripts in a sandbox or non-production lab environment first. Ensure that any alert mechanism (email, Teams webhook) configured in the script is correctly set up to avoid notification fatigue.

Designing the Core Parsing Function

The core of our solution is a custom function named Check-CPUSpike. This function encapsulates the logic required to query the event log, filter for specific CPU-related events, and evaluate the severity.

We will use the Get-WinEvent cmdlet, which is more efficient than the legacy Get-EventLog. We filter for Event ID 7035 or similar generic application errors that often accompany performance degradation, specifically looking for entries where the source indicates a performance counter failure or high load warnings.

function Check-CPUSpike {
    Param (
        [Parameter(Mandatory=$true)]
        [int]$CPUThreshold = 90, # Percentage threshold to trigger an alert

        [Parameter(Mandatory=$false)]
        [string]$LogSource = "System",

        [Parameter(Mandatory=$false)]
        [int]$MaxEventsToCheck = 50
    )

    Write-Host "Scanning $LogSource log for performance events..." -ForegroundColor Cyan

    # Retrieve recent events from the System log
    # We limit results to prevent memory issues on large servers
    $events = Get-WinEvent -LogName $LogSource -MaxEvents $MaxEventsToCheck -ErrorAction SilentlyContinue | Where-Object { $_.Id -eq 7035 -or $_.Id -eq 4104 }

    foreach ($event in $events) {
        $time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

        # Check if the message contains keywords related to high CPU or counter failures
        if ($event.Message -match "(High|Counter|Processor|Exceeded)" -or $event.Id -eq 4104) {
            Write-Host "[ALERT] Detected potential CPU spike or performance issue at $time." -ForegroundColor Red
            Write-Host "Event ID: $($event.Id)" -ForegroundColor Yellow
            Write-Host "Message Snippet: $($event.Message.Substring(0, [Math]::Min($event.Message.Length, 200)))" -ForegroundColor Gray

            # Here you would insert the alert logic (e.g., Send-MailMessage)
            # For this demo, we simply log to console with a visual indicator
        }
    }

    if ($events.Count -eq 0) {
        Write-Host "No critical performance events found in the last $($MaxEventsToCheck) entries." -ForegroundColor Green
    }
}

Code Explanation:
1. Parameters: The function accepts a $CPUThreshold (though strictly speaking, NPM event logs often report failures rather than raw percentages, this parameter allows flexibility for future integration with WMI queries).
2. Get-WinEvent: This cmdlet fetches events from the specified log name. We limit the count to avoid loading gigabytes of data into memory.
3. Filtering: The Where-Object clause filters for specific Event IDs. Event ID 4104 in the System log often indicates a Kernel Power issue, while generic text matching checks for “High” or “Processor” strings which frequently appear when a CPU spike causes a process to terminate unexpectedly.
4. Output: The script writes colored output to the console, making it easy to spot issues during manual testing.

Implementing the Alert Trigger Mechanism

Parsing the log is only half the battle; the system must react. In a real-world scenario, you would integrate this function with an email server or a messaging platform like Microsoft Teams. Below is an example of how to append an alert trigger using Send-MailMessage.

function Send-CPUAlert {
    Param (
        [string]$Recipient = "admin@example.com",
        [string]$Subject = "CRITICAL: CPU Spike Detected on $(hostname)",
        [string]$Body
    )

    try {
        # Check for SMTP server availability
        $smtpServer = "smtp.example.com" 
        if (Test-NetConnection -ComputerName $smtpServer -Port 25) {
            Send-MailMessage -To $Recipient -From "monitoring@localhost" -Subject $Subject -Body $Body -SmtpServer $smtpServer -UseDefaultCredentials
            Write-Host "Alert email sent successfully." -ForegroundColor Green
        } else {
            Write-Warning "SMTP connection failed. Check network connectivity to $($smtpServer)."
        }
    } catch {
        Write-Error "Failed to send alert: $_"
    }
}

Important Considerations:
* Security: Never hardcode passwords in scripts. Use environment variables or certificate-based authentication for SMTP credentials.
* Rate Limiting: Sending too many emails can trigger spam filters. Ensure your logic includes a cooldown period (e.g., wait 1 hour before re-alerting on the same condition) to prevent flooding.

Scheduling the Automated Workflow

A script that runs once is not an automation solution. To make this effective, we must schedule it to run periodically using Task Scheduler. This creates a robust monitoring loop without requiring a dedicated agent like Nagios or Zabbix.

  1. Save the Script: Save the combined functions into a file named Monitor-CPU.ps1 in a secure directory (e.g., C:\Scripts\Monitoring).
  2. Create the Task: Open “Task Scheduler” on the server.
  3. New Task Configuration:
    • General Tab: Select “Run with highest privileges.” This ensures access to the System log.
    • Triggers Tab: Set the task to start “On a schedule.” Choose “Daily” or “Hourly” depending on your tolerance for downtime. Set the recurrence to run every 15 minutes for high-frequency monitoring.
    • Actions Tab: Select “Start a program.”
      • Program/Script: powershell.exe
      • Arguments: -ExecutionPolicy Bypass -File "C:\Scripts\Monitoring\Monitor-CPU.ps1"
      • Start In: C:\Scripts\Monitoring
  4. Verification: After scheduling, manually trigger the task once to verify it executes without errors. Check the “History” tab in Task Scheduler to ensure the script ran and completed successfully.

Common Errors and Troubleshooting

When deploying this solution, you may encounter specific issues related to permissions or script execution policies.

  • Error: Access Denied: If Get-WinEvent fails, the script is likely running under a standard user account without local admin rights.
    • Fix: Open Task Scheduler, go to the “General” tab of your created task, and check “Run with highest privileges.”
  • Error: Execution Policy Restricted: On many production Windows servers, the default execution policy is Restricted.
    • Fix: The script arguments include -ExecutionPolicy Bypass, which temporarily overrides this restriction for the current session. This is safe for scheduled tasks but should not be used for interactive login sessions on sensitive systems.
  • Error: SMTP Timeout: If email alerts fail, it is usually due to network firewalls blocking port 25 or missing SSL certificates.
    • Fix: Update the Send-MailMessage parameters to use -Port 587 and add -UseSsl $true along with valid credentials for your organization’s mail server.

Student Practice Task: Building a Lab Environment

For students and junior engineers practicing this skill, set up a virtual machine (e.g., using Hyper-V or VMware).
1. Install Windows Server Evaluation Edition.
2. Create a batch file that uses taskkill /F /IM explorer.exe to simulate a CPU spike by freezing the interface (note: this is destructive for the session but useful for testing recovery scripts). Alternatively, use stress-ng if available via WSL or a Linux VM alongside Windows.
3. Deploy the PowerShell script created above.
4. Configure Task Scheduler to run the script every 5 minutes.
5. Observe how the script detects the anomaly and logs the event.

By mastering this workflow, you gain valuable experience in legacy system monitoring, a skill set still highly relevant for maintaining on-premise infrastructure where modern agents may not be feasible.

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.