With the advent of virtual machines came the notion that because hard drives can be expanded in the future you should set them to be as small as they possibly can be at the start. As a result our technicians are constantly having to clean up C:\ to make space.
# Log Off All Disconnected Users
$DisconnectedSessions = quser | Where-Object { $_ -match 'Disc' } | ForEach-Object { $fields = $_ -split ' +'; @{ UserName = $fields[1]; SessionId = $fields[2] } }
foreach ($Session in $DisconnectedSessions) {
Write-Host "Logging off user: $($Session.UserName) with session id: $($Session.SessionId)"
logoff $Session.SessionId
}
# Delete All Recycle Bins - Don't worry, they will automatically be recreated when a user logs in
Get-ChildItem -Path 'C:\$Recycle.Bin' -Force | Remove-Item -Recurse -Force
# Delete Contents of C:\Windows\Temp
Remove-Item -Path "C:\Windows\Temp\*" -Force -Recurse
# Delete Files or Folders in C:\Temp Older Than 14 Days
Get-ChildItem -Path "C:\Temp\*" -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-14) } | Remove-Item -Force -Recurse
# Delete Crash Dump Files in C:\Windows\Minidump and C:\Windows
Remove-Item -Path "C:\Windows\Minidump\*" -Force -Recurse
Remove-Item -Path "C:\Windows\*.dmp" -Force
# Delete Log Files in C:\Windows\Logs\CBS Older Than 14 Days
Get-ChildItem -Path "C:\Windows\Logs\CBS\*" -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-14) } | Remove-Item -Force
# Delete Contents of C:\Windows\Prefetch
Remove-Item -Path "C:\Windows\Prefetch\*" -Force -Recurse
# Delete Contents of C:\Windows\SoftwareDistribution\Download
Remove-Item -Path "C:\Windows\SoftwareDistribution\Download\*" -Force -Recurse
# Empty Your Recycle Bin - If this on PowerShell 5 or newer can you use the much more eliquent" Clear-RecycleBin -Force
(New-Object -ComObject Shell.Application).Namespace(0x0a).Items() | ForEach-Object { $_.InvokeVerb("delete") }
To make that task easier we have this simple script that we thought you would find useful. We have comments on every line so the script is self explanatory but if you have any questions just ask us in the comments section below.
CLARIFICATION: Ignore the errors in red when you run it as they refer to files that are in-use and can’t be deleted, which is fine.
0 Comments