MSDN Documentation

Microsoft Developer Network

PowerShell Monitoring Scripts

This article explores the creation and utilization of PowerShell scripts for effective system and application monitoring. PowerShell provides a robust and flexible platform for automating tasks, retrieving system information, and responding to events, making it an indispensable tool for system administrators and DevOps engineers.

Why Use PowerShell for Monitoring?

PowerShell offers several advantages for monitoring:

  • Automation: Automate routine checks and alerts.
  • Data Collection: Gather detailed performance metrics and event logs.
  • Integration: Seamlessly integrate with Windows services, WMI, and .NET.
  • Customization: Tailor scripts to specific monitoring needs.
  • Remote Management: Execute scripts on remote machines without direct access.

Key Areas for Monitoring

PowerShell scripts can be developed to monitor various aspects of your infrastructure:

  • Performance Metrics: CPU usage, memory utilization, disk I/O, network traffic.
  • Event Logs: System, application, and security event logs for errors and critical events.
  • Service Status: Ensure critical Windows services are running.
  • Disk Space: Monitor free disk space on volumes.
  • Process Monitoring: Track specific processes and their resource consumption.
  • Network Connectivity: Test connectivity to critical servers or services.

Example: Monitoring Disk Space

Here's a simple PowerShell script to check disk space and alert if it falls below a certain threshold:


# Define the drive letter to monitor
$DriveLetter = "C:"

# Define the warning threshold (e.g., 20% free space)
$WarningThresholdPercent = 20

# Get the disk space information
$Disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='$DriveLetter'"

# Calculate the free space percentage
$FreeSpacePercent = ($Disk.FreeSpace / $Disk.Size) * 100

# Check if free space is below the threshold
if ($FreeSpacePercent -lt $WarningThresholdPercent) {
    $Subject = "ALERT: Low Disk Space on $($env:COMPUTERNAME) - $DriveLetter"
    $Body = @"
    Low disk space detected on server: $($env:COMPUTERNAME)
    Drive: $DriveLetter
    Total Size: $([math]::Round($Disk.Size / 1GB, 2)) GB
    Free Space: $([math]::Round($Disk.FreeSpace / 1GB, 2)) GB
    Free Space Percentage: $([math]::Round($FreeSpacePercent, 2))%

    Please investigate and free up disk space.
    "@

    # Send an email alert (configure your SMTP server and recipient)
    # Send-MailMessage -To "admin@example.com" -From "monitor@example.com" -Subject $Subject -Body $Body -SmtpServer "smtp.example.com"

    Write-Host $Subject
    Write-Host $Body
    Write-Host "Email alert would be sent to admin@example.com"
} else {
    Write-Host "Disk space on $DriveLetter is healthy. Free space: $([math]::Round($FreeSpacePercent, 2))%"
}
                
Note: To enable email alerts, uncomment the Send-MailMessage cmdlet and configure the -To, -From, and -SmtpServer parameters with your specific details.

Example: Monitoring Service Status

This script checks if a specific service is running and restarts it if it's stopped:


# Define the service name to monitor
$ServiceName = "Spooler" # Example: Print Spooler

# Get the service status
$Service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue

if ($Service) {
    if ($Service.Status -eq "Running") {
        Write-Host "Service '$ServiceName' is running."
    } else {
        Write-Host "Service '$ServiceName' is not running. Attempting to start..."
        try {
            Start-Service -Name $ServiceName
            Write-Host "Service '$ServiceName' started successfully."
        } catch {
            Write-Error "Failed to start service '$ServiceName'. Error: $($_.Exception.Message)"
        }
    }
} else {
    Write-Warning "Service '$ServiceName' not found on this machine."
}
                

Best Practices for Monitoring Scripts

  • Error Handling: Implement robust error handling (e.g., using try-catch blocks) to gracefully manage unexpected situations.
  • Logging: Log script execution results, including successes, failures, and important events, to a file or event log.
  • Clear Output: Provide clear and concise output, making it easy to understand the status of monitored resources.
  • Parameterization: Use parameters to make scripts more flexible and reusable.
  • Scheduling: Schedule scripts to run at regular intervals using Windows Task Scheduler.
  • Centralized Management: Consider using PowerShell Desired State Configuration (DSC) or other orchestration tools for managing and deploying monitoring scripts across multiple servers.

Further Reading

Explore the official Microsoft documentation for more advanced PowerShell concepts and cmdlets related to monitoring and system administration.