When running database workloads, compiling large source repositories, or generating Docker containers within the Windows Subsystem for Linux (WSL 2), virtual disk consumption can increase rapidly without warning. Running out of allocated virtual drive space causes sudden compilation failures, corrupt package caches, and database write errors. By authoring an automated PowerShell monitoring script integrated with native Windows Toast notifications, developers can receive proactive desktop alerts before storage thresholds are breached.
Understanding WSL 2 Filesystem Storage Boundaries
Effective monitoring requires tracking two interrelated storage boundaries:
- Internal ext4 Capacity: The logical disk space available inside the Linux virtual filesystem as reported by
df. - Host VHDX Footprint: The physical size of the
ext4.vhdxcontainer on the host Windows NTFS partition, which impacts available host disk space. - Notification Thresholds: Setting warning thresholds (e.g., at 85% capacity) provides sufficient lead time to trigger file cleanup or disk expansion before catastrophic write failures occur.
Creating the PowerShell Monitoring and Alert Script
Create a dedicated PowerShell script that inspects internal disk utilization and triggers native Windows notifications when thresholds are exceeded:
# Define script storage path
$scriptPath = "$env:USERPROFILE\Documents\Check-WSLDiskSpace.ps1"
$scriptContent = @'
# Threshold percentage for warning alert
$WarningThreshold = 85
# Execute Linux df command to retrieve root partition percentage
try {
$dfOutput = wsl -e df -P / | Select-Object -Skip 1
$fields = $dfOutput -split 's+'
$usePercentage = [int]($fields[4] -replace '%', '')
$availableSpace = $fields[3]
Write-Output "WSL Root Utilization: $usePercentage%"
if ($usePercentage -ge $WarningThreshold) {
# Construct Windows Toast Notification
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
$template = @"
WSL 2 Storage Warning
Root filesystem has reached $usePercentage% capacity ($availableSpace KB remaining). Please run cleanup or expand VHDX.
"@
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template)
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("WSL Storage Monitor").Show($toast)
}
} catch {
Write-Error "Failed to query WSL disk status: $_"
}
'@
$scriptContent | Out-File -FilePath $scriptPath -Encoding utf8
Testing Notification Delivery Manually
Verify that the script executes cleanly and displays toast notifications properly:
- Open a PowerShell terminal.
- Execute the script directly:
& "$env:USERPROFILE\Documents\Check-WSLDiskSpace.ps1" - If your current disk utilization is below 85%, temporarily modify
$WarningThreshold = 10in the script to trigger a test notification banner on your desktop.
Scheduling Automated Periodic Background Checks
Automate execution by registering a background scheduled task using PowerShell:
# Create scheduled task action running hidden
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File `"$env:USERPROFILE\Documents\Check-WSLDiskSpace.ps1`""
# Trigger monitoring every 4 hours daily
$trigger = New-ScheduledTaskTrigger -Daily -At 8am
$trigger.RepetitionInterval = (New-TimeSpan -Hours 4)
# Register the scheduled task
Register-ScheduledTask -TaskName "WSL_Disk_Monitor" -Action $action -Trigger $trigger -Description "Monitors WSL 2 virtual disk usage and sends alerts."
Recommended Cleanup Actions Upon Receiving an Alert
When an alert notifies you that storage utilization is critical, execute the following quick remediation steps inside WSL:
- Clean Package Caches: Run
sudo apt clean && sudo apt autoremove -yto purge downloaded Debian packages. - Prune Docker Volumes: Run
docker system prune -a --volumesto remove orphaned build layers. - Trim Virtual Filesystem: Execute
sudo fstrim -avto allow the underlying Windows sparse VHD to release free sectors.