Skip to content

Instantly share code, notes, and snippets.

@michaelsanford
Last active June 20, 2025 22:12
Show Gist options
  • Save michaelsanford/b74359375a617122bcf375efa20f41b6 to your computer and use it in GitHub Desktop.
Save michaelsanford/b74359375a617122bcf375efa20f41b6 to your computer and use it in GitHub Desktop.
Windows 11 Maintenance (DISM, SFC, compact VM disks)
#Requires -RunAsAdministrator
$logFile = "$env:USERPROFILE\Desktop\WindowsMaintenance_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
Start-Transcript -Path $logFile -Append
"Starting Windows maintenance routine..."
if ($wslFeature.State -eq 'Enabled') {
"Shutting down WSL..."
wsl --shutdown
}
$drives = Get-Volume | Where-Object {
$_.DriveLetter -match '^[A-Z]$' -and $_.FileSystem -ne $null -and $_.DriveType -eq "Fixed"
}
Start-MpScan -ScanType QuickScan
DISM /Online /Cleanup-Image /RestoreHealth
sfc /scannow
foreach ($drive in $drives) {
$letter = $drive.DriveLetter
"Running chkdsk on drive $letter..."
chkdsk.exe /scan "${letter}:"
}
"Optimizing local VHDX files..."
Get-ChildItem -Path $Env:LOCALAPPDATA -Recurse -Filter *.vhdx -ErrorAction SilentlyContinue | ForEach-Object {
"Optimizing VHD: $($_.FullName)"
Optimize-VHD -Path $_.FullName -Mode Full
}
foreach ($drive in $drives) {
$letter = $drive.DriveLetter
"Optimizing drive $letter..."
Optimize-Volume -DriveLetter $letter -NormalPriority -Verbose
}
"Cleaning temporary files..."
Get-ChildItem "$env:TEMP" -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
"Disk space report:"
foreach ($drive in $drives) {
$letter = $drive.DriveLetter
$freeGB = "{0:N1}" -f ($drive.SizeRemaining / 1GB)
"Drive ${letter}: $freeGB GB free"
}
"Reviewing recent system errors..."
$errors = Get-WinEvent -LogName System -FilterXPath "*[System[(Level=1 or Level=2) and TimeCreated[timediff(@SystemTime) <= 86400000]]]"
if ($errors.Count -gt 0) {
"Errors found in the System log:"
$errors | Format-Table TimeCreated, Id, Message -AutoSize
} else {
"No critical or error-level events in the last 24 hours."
}
# if (Get-Module -ListAvailable -Name PSWindowsUpdate) {
# "Checking for Windows Updates..."
# Import-Module PSWindowsUpdate
# Get-WindowsUpdate -AcceptAll -Install -AutoReboot
# } else {
# "PSWindowsUpdate module not found. Skipping update check."
# }
"Windows maintenance complete!"
Stop-Transcript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment