Create a Disk Space Health Check Routine with PowerShell and Task Scheduler

  • Thread Author

Create a Disk Space Health Check Routine with PowerShell and Task Scheduler​

Difficulty: Intermediate | Time Required: 15-25 minutes
Introduction
Keeping an eye on disk space is a simple but effective way to prevent performance slowdowns and unexpected outages. A small routine that runs automatically can catch low space on boot drives before it becomes a problem. In this guide, you’ll set up a PowerShell script that checks all mounted volumes, logs results, and raises a warning if space gets tight. Then you’ll schedule it with Task Scheduler to run on a daily (or weekly) cadence. This approach works well on Windows 10 and Windows 11, and it leverages built-in tools most admins already have.
Prerequisites
  • Windows 10 or Windows 11 PC with PowerShell 5.1 (default on most systems) or PowerShell 7.x installed.
  • Admin rights to create or modify scheduled tasks (Task Scheduler).
  • A dedicated folder to store the script and log files, e.g. C:\Scripts\ and C:\Logs.
  • Basic familiarity with editing text files and running PowerShell scripts.
  • Optional: a dedicated email/alert method if you want notifications beyond log files (not required for the core routine).
Step-by-step instructions
1) Create the PowerShell script
  • Create a new folder for the script and logs:
    • C:\Scripts
    • C:\Logs (or a path you prefer)
  • Create a new PowerShell script file named DiskSpaceHealthCheck.ps1 in C:\Scripts with the following content. This script collects disk space data for all volumes with a drive letter, computes free space percentages, logs the results, and writes an alert to the Windows Event Log if any volume is running low.
Code:
# DiskSpaceHealthCheck.ps1
# Purpose: Check disk space on all mounted volumes and log results.
# Author: You
# Date: (auto) # Configurable thresholds
$thresholdPct = 15 # Alert if free space is <= this percentage
$thresholdGB = 10 # Alert if free space is <= this many GB # Log location
$logDir = "$env:USERPROFILE\Documents\DiskSpaceHealthCheck"
if(!(Test-Path $logDir) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
$logFile = Join-Path -Path $logDir -ChildPath ("DiskSpaceHealthCheck_{0}.log" -f (Get-Date -Format "yyyyMMdd_HHmmss") # Header
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$reportLines = @
$reportLines += "Disk Space Health Check Report - $timestamp"
$reportLines += "Thresholds: Free space <= ${thresholdPct}% or <= ${thresholdGB}GB"
$reportLines += "" # Gather volume info
$vols = Get-Volume -ErrorAction SilentlyContinue
$lowDisks = @ foreach($v in $vols) { if([string]::IsNullOrEmpty($v.DriveLetter) { continue } $size = [double]$v.Size $free = [double]$v.SizeRemaining if($size -le 0) { continue } $pct = [math]::Round(($free / $size) * 100, 2) $freeGB = [math]::Round($free / 1GB, 2) $sizeGB = [math]::Round($size / 1GB, 2) $line = "Drive $($v.DriveLetter): Size=${sizeGB}GB, Free=${freeGB}GB (${pct}%)" if($pct -le $thresholdPct -or $free -lt ($thresholdGB * 1GB) { $line += " [LOW SPACE ALERT]" $lowDisks += [pscustomobject]@{ Drive = $v.DriveLetter SizeGB = $sizeGB FreeGB = $freeGB FreePct = $pct } } $reportLines += $line
} # Event log alert (optional)
$logName = "DiskSpaceHealth"
$source = "DiskSpaceHealthCheck"
if(!(Get-EventLog -LogName $logName -ErrorAction SilentlyContinue) { # Create the event source if the log doesn't exist yet New-EventLog -LogName $logName -Source $source -ErrorAction SilentlyContinue | Out-Null
}
if($lowDisks.Count -gt 0) { $alertMsg = "Low disk space on: " + ($lowDisks | ForEach-Object { "$($_.Drive): $($_.FreePct)% free" }) -join ", " Write-EventLog -LogName $logName -Source $source -EventId 1001 -EntryType Warning -Message $alertMsg
} # Write to log file
$reportLines | Out-File -FilePath $logFile -Encoding UTF8 # Optional: print to console for manual testing
$reportLines | ForEach-Object { Write-Output $_ } # End
Notes:
  • If you’re using a Windows where Get-Volume isn’t available, you can try Get-CimInstance or a fallback (but Get-Volume covers most modern setups well).
  • The script creates a per-run log file under your Documents folder. You can rotate or archive logs later if you want to limit disk usage.
2) Test the script manually
  • Open PowerShell (as Administrator) and run:
    • Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
    • & "C:\Scripts\DiskSpaceHealthCheck.ps1"
  • Check the log file in your Documents/DiskSpaceHealthCheck for a new entry with the current date/time.
  • If you added alerting logic, verify that Event Viewer contains a DiskSpaceHealth event under the DiskSpaceHealth log when a low disk is detected.
3) Schedule the script with Task Scheduler
Option A: GUI (recommended for most users)
  • Open Task Scheduler (search for “Task Scheduler” in the Start menu).
  • In the right pane, choose Create Task (not “Create Basic Task”).
  • General tab:
    • Name: Disk Space Health Check
    • Description: Checks all volumes for free space and logs results.
    • Run whether user is logged on or not
    • Run with highest privileges
    • Configure for: Windows 10/11 (your edition)
  • Triggers tab:
    • New…
    • Begin the task: On a schedule
    • Daily or Weekly, set a time (e.g., every day at 09:00)
    • Enable
  • Actions tab:
    • New…
    • Action: Start a program
    • Program/script: powershell.exe
    • Add arguments: -ExecutionPolicy Bypass -File "C:\Scripts\DiskSpaceHealthCheck.ps1" -NoProfile
    • Start in: C:\Scripts
  • Conditions tab:
    • You can leave as default, or require the computer to be on AC power (recommended for laptops).
  • Settings tab:
    • Allow task to be run on demand
    • If the task fails, restart every 5 minutes, up to 3 retries
    • Stop the task if it runs longer than 1 hour (adjust as needed)
  • OK, provide admin credentials when prompted.
Option B: PowerShell approach (advance users)
  • You can also create a scheduled task via PowerShell. Here is a compact example to get you started (run as Administrator):
Code:
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy Bypass -File `"`C:\Scripts\DiskSpaceHealthCheck.ps1`" -NoProfile"
$trigger = New-ScheduledTaskTrigger -Daily -At 09:00
Register-ScheduledTask -TaskName "Disk Space Health Check" -Action $action -Trigger $trigger -Description "Daily disk space check" -User "SYSTEM" -RunLevel Highest
4) Verify and test the scheduled task
  • In Task Scheduler, locate the Disk Space Health Check task and run it manually once to verify the script executes and creates a log file.
  • Confirm the log file appears in your chosen log directory and contains the expected entries.
  • If you configured event logging, open Event Viewer (Windows Logs > DiskSpaceHealth) to see the alerts when appropriate.
Tips and troubleshooting notes
  • Execution policy: If your environment restricts PowerShell scripts, you may need to set the policy for the session or sign the script. For testing, you can bypass with -ExecutionPolicy Bypass.
  • Running as administrator: While the script can query volumes without admin rights, scheduling it with highest privileges and “Run whether user is logged on or not” ensures it runs smoothly and can write to logs and the event log.
  • Drive letters: Get-Volume returns only volumes with a DriveLetter. If you have script-driven or hidden volumes without letters, you’ll need a different approach; for most desktops and laptops, the common drives (C:, D:, etc. will be covered.
  • Log management: If you want to avoid piling up logs, add a rotation strategy (e.g., keep last 14 logs) by adding a short routine that deletes older files or compresses them periodically.
  • Notifications: If you’d like immediate alerts, you can extend the script to email you using Send-MailMessage or a configured SMTP relay, but be mindful of credential security. For many admins, the Windows Event Log alert suffices as a centralized notification.
  • Windows version notes: Get-Volume is available on Windows 8/10/11 and works reliably with PowerShell 5.1 and later. If you’re on a very old system, you might fallback to other WMI/CIM-based methods, but modern Windows versions are fully supported.
Conclusion
This Disk Space Health Check routine gives you a lightweight, automatic backstop against disk space issues. By combining a straightforward PowerShell script with a scheduled task, you get regular visibility into drive space, a persistent log trail, and proactive alerts when space runs low. It’s especially helpful for servers, desktops with multiple drives, or devices that handle data-heavy workloads.
Key takeaways
  • Automates disk space monitoring on Windows 10/11 with a concise PowerShell script.
  • Logs daily results and flags low-space conditions via the Windows Event Log.
  • Easy to adapt thresholds, log location, and schedule to fit your environment.
  • Enhances reliability by preemptively catching space issues before they impact performance.

This tutorial was generated to help WindowsForum.com users get the most out of their Windows experience.
 

Back
Top