Keeping Windows Server 2022 healthy means regularly freeing up disk space and managing log files. Over the time, unnecessary files, old logs, and leftover update data can eat up storage space and even slow down the server performance. However we can automate disk cleanup and log management using following PowerShell script.
# Windows Server 2022: Disk Space & Log Cleanup Script
# Author: vLookupHub
# Date: 2025-06-14
# Description: Cleans up common log and temp files to free disk space on Windows Server 2022.
# Run as Administrator!
# =================== CONFIGURATION ===================
# Set retention period (in days) for logs to keep
$LogRetentionDays = 14
# Specify locations to clean
$TempFolders = @(
"$env:SystemRoot\Temp",
"$env:TEMP",
"C:\Windows\Temp"
)
$UserTempFolders = Get-ChildItem -Path "C:\Users" -Directory | ForEach-Object {
"$($_.FullName)\AppData\Local\Temp"
}
$LogFolders = @(
"C:\Windows\Logs",
"C:\Windows\System32\LogFiles",
"C:\inetpub\logs\LogFiles"
)
# ==================== FUNCTIONS ====================
function Remove-OldFiles {
param (
[string[]]$Paths,
[int]$Days = 14
)
foreach ($Path in $Paths) {
if (Test-Path $Path) {
Write-Host "Cleaning files older than $Days days in $Path..."
Get-ChildItem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-$Days) } |
Remove-Item -Force -ErrorAction SilentlyContinue
} else {
Write-Host "Path not found: $Path"
}
}
}
function Clean-WindowsUpdateCache {
Write-Host "Cleaning Windows Update cache..."
Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Windows\SoftwareDistribution\Download\*" -Recurse -Force -ErrorAction SilentlyContinue
Start-Service -Name wuauserv
}
function Clear-RecycleBin {
Write-Host "Emptying recycle bins..."
try {
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
} catch {
Write-Host "Unable to clear recycle bin."
}
}
function Clean-EventLogs {
Write-Host "Clearing Windows Event Logs..."
Get-EventLog -LogName * | ForEach-Object {
try {
Clear-EventLog -LogName $_.Log
} catch {
Write-Host "Failed to clear log: $($_.Log)"
}
}
}
function Run-DiskCleanup {
Write-Host "Running Windows Disk Cleanup (sageset)..."
Start-Process cleanmgr.exe -ArgumentList "/sagerun:1" -Wait
}
# ==================== CLEANUP TASKS ====================
Write-Host "===== Starting Disk Space & Log Cleanup =====" -ForegroundColor Cyan
# 1. Clean System and User Temp folders
Remove-OldFiles -Paths $TempFolders -Days 2
Remove-OldFiles -Paths $UserTempFolders -Days 2
# 2. Clean common log folders
Remove-OldFiles -Paths $LogFolders -Days $LogRetentionDays
# 3. Clean IIS logs (if IIS is installed)
if (Test-Path "C:\inetpub\logs\LogFiles") {
Remove-OldFiles -Paths "C:\inetpub\logs\LogFiles" -Days $LogRetentionDays
}
# 4. Clean Windows Update cache
Clean-WindowsUpdateCache
# 5. Empty Recycle Bin
Clear-RecycleBin
# 6. Clear old Event Logs (optional, uncomment to enable)
# Clean-EventLogs
# 7. Run Disk Cleanup (optional, interactive)
# Run-DiskCleanup
Write-Host "===== Cleanup Complete! =====" -ForegroundColor Green
}
What This Script Does?
This PowerShell script automates several key cleanup tasks
- Deletes Old Temporary Files - It cleans out the Windows temp folders and each user's temp folder, removing files older than 2 days.
- Removes Old Log Files - It targets common log directories, including Windows logs and IIS logs (if IIS is installed), keeping only the last two weeks by default.
- Cleans Windows Update Cache - It safely removes leftover update files that can accumulate after patches and system updates.
- Empties the Recycle Bin - Frees up space by ensuring deleted files are truly gone.
- Clears Event Logs (Optional) - For environments where old event logs aren't needed, this can clear them out. (Uncomment the relevant line in the script if you want this.)
- Runs Windows Disk Cleanup (Optional) - You can launch the built-in Disk Cleanup utility for deeper cleaning. This is interactive and optional.
How to Use the Script
1. Copy the entire script into PowerShell ISE or in notepad save as and name it like Cleanup-WindowsServer2022.ps1. In my case i saved in "C:\Temp" folder
2. We can run it via PowerShell ISE as well, in my case i ran the script via PowerShell ISE directly and it is working as expected. Click on the PowerShell ISE and run as Administrator, paste entire script , make changes as per your requirement and click on Run
3. Right-click on PowerShell and select "Run as administrator" - this script needs admin rights to access system folders. Execute the Script by Navigating to where you saved the script and run (in my case i have saved in c:\temp)
Set-ExecutionPolicy RemoteSigned -Scope Process
.\Cleanup-WindowsServer2022.ps1
4. If you see "Unable to clear recycle
bin" at end of output , it means recycle bin is empty and nothing to
clean.
5. You can adjust $LogRetentionDays and other settings at the top of the script according to what suits to your environment.
Important Note:
- Always test the script on non-production server to make sure it doesn't remove anything critical for the applications.
- If you need to keep certain logs for compliance, back them up before running cleanup.
- Make sure the paths in the script match your server's configuration, especially if you have custom log or temp directories.
- Schedule this script to run weekly using Task Scheduler for hands-off maintenance
Conclusion
Automating disk space and log file cleanup on Windows Server is a proactive step toward maintaining optimal server performance and avoiding unexpected issues due to disk space issue. By using a custom PowerShell script, can easily schedule and perform regular cleanups without manual intervention.
Not only does this approach reduce the risk of performance degradation, but it also improves operational efficiency, saves time, and enhances server reliability. Whether you are managing a single server or an enterprise fleet, automation helps ensure your infrastructure remains healthy, clean, and compliant.
Ckeckout more blogs on vlookuphub