PC Tips & Tricks guides, explanations and reader checklists on whilenetworking.com

Student Project: Automating Disk Space Monitoring with PowerShell to Alert Before Storage Quotas Are Reached

Storage exhaustion is one of the most common causes of unexpected system downtime in enterprise environments. When a drive fills up, services like databases,…

Storage exhaustion is one of the most common causes of unexpected system downtime in enterprise environments. When a drive fills up, services like databases, web servers, and logging mechanisms can fail catastrophically without warning. For IT students and junior engineers, mastering automated monitoring is a critical skill that bridges the gap between reactive troubleshooting and proactive infrastructure management. This guide demonstrates how to build a robust, scheduled PowerShell script that monitors disk space, calculates remaining capacity against defined thresholds, and sends alerts before storage quotas are breached. By automating this task, you eliminate the need for manual checks and ensure that administrators receive timely notifications to initiate cleanup or expansion procedures.

Understanding the Architecture of Disk Monitoring

Before writing code, it is essential to understand how Windows exposes disk information to scripts. The Get-PSDrive cmdlet provides a high-level view of mounted volumes, returning properties such as Name, UsedBytes, and FreeBytes. However, for more granular control over specific physical or logical disks (such as C:, D:, or data partitions on server arrays), the Get-PhysicalDisk or Get-Volume cmdlets are often preferred. In this project, we will utilize Get-CimInstance Win32_LogicalDisk, which is part of the WMI (Windows Management Instrumentation) provider available in almost all versions of Windows Server and Windows 10/11. This approach ensures compatibility across different OS versions without requiring specific module installations.

The logic for monitoring relies on a simple mathematical comparison: if (UsedBytes / TotalBytes) exceeds a defined percentage threshold (e.g., 85%), the system triggers an alert. It is crucial to distinguish between “free space” and “used space.” Many scripts incorrectly check only if free space is zero; however, alerts should trigger when free space drops below a safety margin to allow for temporary spikes in usage.

Prerequisites and Environment Setup

To successfully implement this project, you need a Windows environment with PowerShell 5.1 or later (Windows Server 2016+, Windows 10 v1809+). No external modules are strictly necessary for basic WMI queries, but having PSScriptRunner or PowerShellGet installed can simplify future maintenance. You will also need a method to send alerts; this project uses the built-in Send-MailMessage cmdlet.

Important Note: Using Send-MailMessage requires that you have SMTP server credentials configured on your machine. If your organization has strict security policies, you may be required to use an enterprise mail client (like Outlook) for testing or configure a local relay service. Ensure your test environment is isolated from production networks until the script is verified as safe.

Step 1: Define Configuration Variables and Thresholds

The first step in building a maintainable script is to separate configuration data from logic. This allows you to adjust thresholds without modifying the core code. We will create variables for the disk paths, warning levels, and SMTP settings.

# Define the logical drive letters to monitor
$drivesToMonitor = @("C:", "D:")

# Set threshold percentages. Warning triggers at 85%, Critical at 95%.
$warningThreshold = 85
$criticalThreshold = 95

# SMTP Configuration (Update these with your actual lab or corporate settings)
$smtpServer = "mail.yourdomain.com"
$fromAddress = "storage-alerts@yourdomain.com"
$toAddress = "admin@yourdomain.com"
$subjectPrefix = "[ALERT] Disk Space Warning - "

What this does: These variables define the scope of the monitoring. By using an array for $drivesToMonitor, you can easily add new drives to the script later without rewriting the loop logic. The thresholds are defined as integers representing percentages, making them intuitive to read and modify.

Step 2: Build the Monitoring Logic and Alert Function

Next, we construct the core function that iterates through the specified drives, calculates usage percentages, and decides whether an alert is necessary. We will also include a helper function to send emails safely.

function Send-DiskAlert {
    param(
        [string]$Subject,
        [string]$Body,
        [string]$Sender,
        [string]$Recipient,
        [string]$SmtpServer
    )

    # Note: In a production environment, you would use -Credential to pass secure credentials.
    # For this student project, we assume the user running the script has local admin rights 
    # and the SMTP server allows authenticated relay or is configured for internal use.

    try {
        Send-MailMessage `
            -From $Sender `
            -To $Recipient `
            -Subject $Subject `
            -Body $Body `
            -SmtpServer $SmtpServer `
            -UseDefaultCredentials # Replace with explicit credentials for production
            -Port 25
    } catch {
        Write-Warning "Failed to send email alert: $($_.Exception.Message)"
    }
}

function Test-DiskSpace {
    param([string]$DriveLetter)

    $drive = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$DriveLetter'"

    if ($null -eq $drive) { return } # Skip if drive doesn't exist

    $totalGB = [math]::Round($drive.Size / 1GB, 2)
    $freeGB = [math]::Round($drive.FreeSpace / 1GB, 2)
    $usedPercent = [math]::Round((($drive.Size - $drive.FreeSpace) / $drive.Size) * 100, 2)

    # Determine status based on thresholds
    if ($usedPercent -ge $criticalThreshold) {
        $status = "CRITICAL"
        $message = "Drive $DriveLetter is at $usedPercent% capacity. Immediate action required."
    } elseif ($usedPercent -ge $warningThreshold) {
        $status = "WARNING"
        $message = "Drive $DriveLetter is at $usedPercent% capacity. Plan for expansion soon."
    } else {
        return # No alert needed
    }

    $fullMessage = "System: Storage Monitoring`nStatus: $status`nDrive: $DriveLetter`nTotal Size: ${totalGB} GB`nFree Space: ${freeGB} GB`nUsage: ${usedPercent}%`nDetails: $message"

    # Construct email subject and body
    $emailSubject = "$subjectPrefix$($drive.DeviceID)"
    $emailBody = $fullMessage

    # Trigger the alert sending function
    Send-DiskAlert -Subject $emailSubject -Body $emailBody -Sender $fromAddress -Recipient $toAddress -SmtpServer $smtpServer

    Write-Host "Alert Sent for $DriveLetter: $status" -ForegroundColor Red
}

# Main execution loop
foreach ($drive in $drivesToMonitor) {
    Test-DiskSpace -DriveLetter $drive
}

Expected Results: When run manually, if the C: drive is at 82% capacity, the script will execute silently (no alert). If it is raised to 90%, you will see a red console message and an email will be sent to the configured address. The try/catch block in the email function prevents the entire script from crashing if the SMTP server temporarily rejects the connection.

Step 3: Scheduling the Script for Continuous Monitoring

A manual run is useful for testing, but automation requires scheduling. Windows Task Scheduler is the standard tool for this. You must create a task that runs your script periodically (e.g., every 15 minutes).

  1. Open Task Scheduler via the Start Menu.
  2. Click Create Task.
  3. In the General tab, name it “Disk Space Monitor” and select “Run with highest privileges.”
  4. In the Triggers tab, click New Trigger, set it to repeat every 15 minutes indefinitely.
  5. In the Actions tab, click New, choose “Start a program,” and browse for your .ps1 script file (e.g., C:\Scripts\DiskMonitor.ps1).
  6. Click OK.

Verification Steps: After creating the task, manually trigger it once to ensure the Task Scheduler can execute the script successfully. Check the Event Viewer under Applications and Services Logs > Microsoft > Windows > PowerShell for any execution errors.

Common Mistakes and Troubleshooting

When implementing disk monitoring scripts, several pitfalls frequently arise. One common error is ignoring the difference between logical and physical drives; a script might report an alert on a mounted network drive that has actually failed to mount, leading to false positives. Always verify the DeviceID property returned by WMI matches the actual volume name in File Explorer.

Another frequent mistake involves email authentication. Many organizations block Send-MailMessage from unauthenticated users for security reasons. If you encounter an error stating “550 5.7.1 Relay access denied,” you must configure the SMTP server to accept connections from your local IP or use a secure relay service like Microsoft Exchange Online Protection with proper credentials.

Additionally, scripts should handle non-existent drives gracefully. The code above includes a check (if ($null -eq $drive)) to skip missing volumes, preventing the script from throwing an exception and stopping execution.

Student Practice Task and Industry Application

For students working on this project, the assignment is to deploy the script on a virtual machine (such as a Windows Server evaluation build), intentionally fill the C: drive using a large download or file creation tool until it hits 90%, and verify that the alert is received. Document the steps in a lab report, including screenshots of the Task Scheduler configuration and the email receipt.

In an industry context, this script serves as a foundational component of a larger Storage Observability strategy. While PowerShell alerts are excellent for immediate notification, production environments often integrate these scripts with SIEM platforms like Splunk or Azure Monitor to aggregate data over time. The logic here can be adapted to write JSON output to a file, which can then be ingested by log collectors, providing a seamless bridge between legacy scripting and modern cloud-native monitoring stacks.

By mastering this project, you gain practical experience in Windows administration, automation best practices, and the critical importance of proactive infrastructure health checks.

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.