Disk Cleanup Using Powershell Scripts

Introduction
 
It is often required to delete any un-used or temporary files to keep your disk clean and to avoid disk full errors over period of time just because of growth of temporary and un-used files. It is more important for the servers to have some automated scripts which clean up the disk on regular basis to keep server system healthy.
 
PowerShell Script to Clean up disk on Windows
 
The most common approach is to write batch file or PowerShell script which can be scheduled on planned interval. Below PowerShell Script will clean up the temporary files, recycle bin and run the Windows’s disk clean up wizard.
  1. ##################################################################################  
  2. # DiskCleanUp  
  3. ##################################################################################  
  4.  
  5. ## Variables ####   
  6.    
  7.     $objShell = New-Object -ComObject Shell.Application   
  8.     $objFolder = $objShell.Namespace(0xA)   
  9.       
  10.     $temp = get-ChildItem "env:\TEMP"   
  11.     $temp2 = $temp.Value   
  12.       
  13.     $WinTemp = "c:\Windows\Temp\*"   
  14.       
  15.  
  16.   
  17. # Remove temp files located in "C:\Users\USERNAME\AppData\Local\Temp"   
  18.     write-Host "Removing Junk files in $temp2." -ForegroundColor Magenta    
  19.     Remove-Item -Recurse  "$temp2\*" -Force -Verbose   
  20.       
  21. # Empty Recycle Bin # http://demonictalkingskull.com/2010/06/empty-users-recycle-bin-with-powershell-and-gpo/   
  22.     write-Host "Emptying Recycle Bin." -ForegroundColor Cyan    
  23.     $objFolder.items() | %{ remove-item $_.path -Recurse -Confirm:$false}   
  24.       
  25. # Remove Windows Temp Directory    
  26.     write-Host "Removing Junk files in $WinTemp." -ForegroundColor Green   
  27.     Remove-Item -Recurse $WinTemp -Force    
  28.       
  29. #6# Running Disk Clean up Tool    
  30.     write-Host "Finally now , Running Windows disk Clean up Tool" -ForegroundColor Cyan   
  31.     cleanmgr /sagerun:1 | out-Null    
  32.        
  33.     $([char]7)   
  34.     Sleep 1    
  35.     $([char]7)   
  36.     Sleep 1        
  37.     
  38.     write-Host "Clean Up Task Finished !!!"
  39. ##### End of the Script ##### ad  
Configure PowerShell Script on window’s Scheduled Task
 
On the Actions tab of the Scheduled task wizard click new to set the action for this task to run. Set the Action to start a program.
 
In the programs/script box enter PowerShell. In the Add arguments[optional] enter the value ".\[your powershell script name]" as shown in below figure.