Introduction
Maintaining a clean and efficient Windows system requires regular cleanup of temporary files, recycling bins, and system clutter. While Windows provides built-in cleanup tools, automating this process can save time and ensure consistent system maintenance. This PowerShell script combines multiple cleanup operations into a single, efficient solution.
The Script
##################################################################################
# DiskCleanUp
##################################################################################
## Variables ####
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace(0xA)
$temp = get-ChildItem "env:\TEMP"
$temp2 = $temp.Value
$WinTemp = "c:\Windows\Temp\*"
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Hide-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
#0 hide
[Console.Window]::ShowWindow($consolePtr, 0)
}
Hide-Console
# Remove temp files located in user temp directory
write-Host "Removing Junk files in $temp2." -ForegroundColor Magenta
Remove-Item -Recurse "$temp2\*" -Force -Verbose
# Empty Recycle Bin #
write-Host "Emptying Recycle Bin." -ForegroundColor Cyan
$objFolder.items() | %{ remove-item $_.path -Recurse -Confirm:$false}
# Remove Windows Temp Directory
write-Host "Removing Junk files in $WinTemp." -ForegroundColor Green
Remove-Item -Recurse $WinTemp -Force
# Running Disk Clean up Tool
write-Host "Finally now, Running Windows disk Clean up Tool" -ForegroundColor Cyan
cleanmgr /sagerun:1 | out-Null
$([char]7)
Sleep 1
$([char]7)
Sleep 1
write-Host "Clean Up Task Finished !!!"
##### End of the Script #####
How It Works
This comprehensive disk cleanup script automates several important system cleaning operations:
- Console Management: Implements a hidden console function for cleaner execution
- Temporary File Cleanup: Removes user-specific temporary files from the system
- Recycle Bin Management: Automatically empties the Windows Recycle Bin
- System Temp Cleanup: Cleans the Windows temporary directory
- Disk Cleanup Utility: Runs the built-in Windows Disk Cleanup tool with preset configurations
- Progress Indication: Provides colorful status updates and completion notifications
Conclusion
This advanced disk cleanup script provides a comprehensive solution for system maintenance. It’s perfect for system administrators, IT professionals, or power users who want to maintain system performance through regular cleanup operations. The script combines multiple cleanup tasks into a single, efficient operation, saving time and ensuring consistent system maintenance.
Remember to run this script with administrative privileges and ensure you have backups of any important data before performing system-wide cleanup operations.