Skip to content

Instantly share code, notes, and snippets.

@DonovanDiamond
Forked from synikil/start-cleanup
Last active February 12, 2024 17:45
Show Gist options
  • Save DonovanDiamond/41ec55ab74bc23b6575dc4ac2bc02277 to your computer and use it in GitHub Desktop.
Save DonovanDiamond/41ec55ab74bc23b6575dc4ac2bc02277 to your computer and use it in GitHub Desktop.
Function Start-Cleanup {
<#
.SYNOPSIS
Automate cleaning up a C:\ drive with low disk space
.DESCRIPTION
Cleans the C: drive's Window Temperary files,
the local users Temperary folder, IIS logs(if applicable) and empties the recycling bin.
All deleted files will go into a log transcript in $env:TEMP. By default this
script leaves files that are newer than 7 days old however this variable can be edited.
.EXAMPLE
PS C:\> .\Windows-Cleanup.ps1
Save the file to your hard drive with a .PS1 extention and run the file from an elavated PowerShell prompt.
.NOTES
This script is designed to not cause any problems with the files it deletes, however you should use this at your own risk.
.FUNCTIONALITY
PowerShell v3+
#>
## Allows the use of -WhatIf
[CmdletBinding(SupportsShouldProcess=$True)]
param(
## Delete data older then $daystodelete
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=0)]
$DaysToDelete = 7,
## LogFile path for the transcript to be written to
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)]
$LogFile = ("$env:TEMP\" + (get-date -format "MM-d-yy-HH-mm") + '.log'),
## All verbose outputs will get logged in the transcript($logFile)
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=2)]
$VerbosePreference = "Continue",
## All errors should be withheld from the console
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
$ErrorActionPreference = "SilentlyContinue",
## Reboot automatically once complete (not yet implemented)
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=4)]
$RebootOnceComplete = $false
)
## Begin the timer
$Starters = (Get-Date)
## Check $VerbosePreference variable, and turns -Verbose on
Function global:Write-Verbose ( [string]$Message ) {
if ( $VerbosePreference -ne 'SilentlyContinue' ) {
Write-Host "$Message" -ForegroundColor 'Green'
}
}
## Tests if the log file already exists and renames the old file if it does exist
if(Test-Path $LogFile){
## Renames the log to be .old
Rename-Item $LogFile $LogFile.old -Verbose -Force
} else {
## Starts a transcript in C:\temp so you can see which files were deleted
Write-Host (Start-Transcript -Path $LogFile) -ForegroundColor Green
}
## Writes a verbose output to the screen for user information
Write-Host "Retriving current disk percent free for comparison once the script has completed. " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
## Gathers the amount of disk space used before running the script
$Before = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName,
@{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
@{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f ( $_.Size / 1gb)}},
@{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f ( $_.Freespace / 1gb ) } },
@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f ( $_.FreeSpace / $_.Size ) } } |
Format-Table -AutoSize |
Out-String
## Deletes the contents of the Windows Temp folder.
Get-ChildItem "C:\Windows\Temp\*" -Recurse -Force -Verbose -ErrorAction SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays( - $DaysToDelete)) } | Remove-Item -force -recurse -ErrorAction SilentlyContinue -Verbose
Write-host "The Contents of Windows Temp have been removed successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
## Deletes all files and folders in user's Temp folder older then $DaysToDelete
Get-ChildItem "C:\users\*\AppData\Local\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays( - $DaysToDelete))} |
Remove-Item -force -recurse -ErrorAction SilentlyContinue -Verbose
Write-Host "The contents of `$env:TEMP have been removed successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
## Removes all files and folders in user's Temporary Internet Files older then $DaysToDelete
Get-ChildItem "C:\users\*\AppData\Local\Microsoft\Windows\Temporary Internet Files\*" `
-Recurse -Force -Verbose -ErrorAction SilentlyContinue |
Where-Object {($_.CreationTime -lt $(Get-Date).AddDays( - $DaysToDelete))} |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue -Verbose
Write-Host "All Temporary Internet Files have been removed successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
## Cleans up Internet Explorer cache
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatCache\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatCache\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatCache\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up Internet Explorer cache
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatUaCache\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatUaCache\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Windows\IECompatUaCache\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up Internet Explorer download history
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Windows\IEDownloadHistory\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\IEDownloadHistory\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Windows\IEDownloadHistory\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up Internet Cache
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCache\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCache\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Windows\INetCache\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up Internet Cookies
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCookies\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Windows\INetCookies\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Windows\INetCookies\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up terminal server cache
if (Test-Path "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\") {
Remove-Item -Path "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Cleans up crash dumps
if (Test-Path "C:\Users\*\AppData\Local\CrashDumps\") {
Remove-Item -Path "C:\Users\*\AppData\Local\CrashDumps\*" -Force -Recurse -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\Users\*\AppData\Local\CrashDumps\ does not exist. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Removes the hidden recycling bin.
if (Test-path 'C:\$Recycle.Bin'){
Remove-Item 'C:\$Recycle.Bin' -Recurse -Force -Verbose -ErrorAction SilentlyContinue
} else {
Write-Host "C:\`$Recycle.Bin does not exist, there is nothing to cleanup. " -NoNewline -ForegroundColor DarkGray
Write-Host "[WARNING]" -ForegroundColor DarkYellow -BackgroundColor Black
}
## Turns errors back on
$ErrorActionPreference = "Continue"
## Checks the version of PowerShell
## If PowerShell version 4 or below is installed the following will process
if ($PSVersionTable.PSVersion.Major -le 4) {
## Empties the recycling bin, the desktop recyling bin
$Recycler = (New-Object -ComObject Shell.Application).NameSpace(0xa)
$Recycler.items() | ForEach-Object {
## If PowerShell version 4 or bewlow is installed the following will process
Remove-Item -Include $_.path -Force -Recurse -Verbose
Write-Host "The recycling bin has been cleaned up successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
}
} elseif ($PSVersionTable.PSVersion.Major -ge 5) {
## If PowerShell version 5 is running on the machine the following will process
Clear-RecycleBin -DriveLetter C:\ -Force -Verbose
Write-Host "The recycling bin has been cleaned up successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
}
## Starts cleanmgr.exe
Function Start-CleanMGR {
Try{
Write-Host "Windows Disk Cleanup is running. " -NoNewline -ForegroundColor Green
Start-Process -FilePath Cleanmgr -ArgumentList '/sagerun:1' -Wait -Verbose
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
}
Catch [System.Exception]{
Write-host "cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -ForegroundColor Red -NoNewline
Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor black
}
} Start-CleanMGR
## gathers disk usage after running the cleanup cmdlets.
$After = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName,
@{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
@{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f ( $_.Size / 1gb)}},
@{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f ( $_.Freespace / 1gb ) } },
@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f ( $_.FreeSpace / $_.Size ) } } |
Format-Table -AutoSize | Out-String
## Stop timer
$Enders = (Get-Date)
## Calculate amount of seconds your code takes to complete.
Write-Verbose "Elapsed Time: $(($Enders - $Starters).totalseconds) seconds
"
## Sends hostname to the console for ticketing purposes.
Write-Host (Hostname) -ForegroundColor Green
## Sends the date and time to the console for ticketing purposes.
Write-Host (Get-Date | Select-Object -ExpandProperty DateTime) -ForegroundColor Green
## Sends the disk usage before running the cleanup script to the console for ticketing purposes.
Write-Verbose "
Before: $Before"
## Sends the disk usage after running the cleanup script to the console for ticketing purposes.
Write-Verbose "After: $After"
## Completed Successfully!
Write-Host (Stop-Transcript) -ForegroundColor Green
Write-host "
Script finished " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
}
start-cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment