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.
- ##################################################################################
- # DiskCleanUp
- ##################################################################################
-
- ## Variables ####
-
- $objShell = New-Object -ComObject Shell.Application
- $objFolder = $objShell.Namespace(0xA)
-
- $temp = get-ChildItem "env:\TEMP"
- $temp2 = $temp.Value
-
- $WinTemp = "c:\Windows\Temp\*"
-
-
-
- # Remove temp files located in "C:\Users\USERNAME\AppData\Local\Temp"
- write-Host "Removing Junk files in $temp2." -ForegroundColor Magenta
- Remove-Item -Recurse "$temp2\*" -Force -Verbose
-
- # Empty Recycle Bin # http://demonictalkingskull.com/2010/06/empty-users-recycle-bin-with-powershell-and-gpo/
- 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
-
- #6# 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 ##### 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.