[How To] clear Temp files using PowerShell
Have you ever logged in to servers just to clear out the free space on the C: drive or received an alert from the monitoring system for disk space as below?
The disk C: on computer Server1.domain.com is running out of disk space. The value that exceeded the threshold is 5% free space.
I’m pretty sure all the IT Administrators have come across this situation including the home users who saved large files in their system drive/ C: drive. if you are one of them, I will give you the easiest way to clear those unwanted files which are saved in your C: in few different locations and are not necessarily important for the user or for the computer applications.
Based on the user/IT Admin’s requirements, I have created multiple versions of this solutions. Here in this article, I will be explaining exactly what you are going to clear when you follow my method as you might think / afraid of deleting the important files in C: drive.
Here in this article, I will be showing you the easiest method to clear files in below locations by using the simple PowerShell Scripts
1. C:\Windows\Temp
The files that you see in the C:\Windows\Temp\ folder are some temporary files created by different Windows operations, like installing Updates. You can safely delete these files off from that folder
2. C:\Users\%UserName%\Appdata\Local\Temp
This folder is used by some applications which you may have downloaded from the internet including Microsoft’s own software which is delivered to you as a compressed file with the extension of .Msi. when you run this kind of applications, they will extract the required files to this folder temporarily and then use them to install the application in your system. in addition, few applications may use this folder to keep some required files temporarily when the application is running. However, you don’t have to panic for this kind of the files as they are locked when they are being used and you can’t delete them.
3. C:\Windows\SoftwareDistribution
The Software Distribution folder in the Windows operating system is a folder is used to temporarily store files which may be required to install Windows Update on your computer. It is used for Windows Update and maintained by WUAgent. files downloaded into this folder are leftover even when the Windows update is completed which will be consuming space in the drive.
Method 1.
- In this method, I would like to let the user decide if he wants to clear the files in the directory mentioned and then act according to his input.
Note: I will be assuming that you have the PowerShell Execution Policy set to allow the scripts.
Download the PowerShell Script file to your local system
change the directory of PowerShell to the location where you saved the downloaded Script
save the below script
Enter “Y” for Yes if you want to delete the files in the mentioned directory. if you don’t wish to delete, enter “N” for No at any stage.
Run the command ./ClearTempFiles-V1.Ps1
In the Above Screenshot, I have run the saved the file in C:\ and run it from PowerShell and Selected “Y” to clear the Temp folder and “N” to not to clear the files in SoftwareDistribution Folder just to show you how it works.
Method 2.
This method will clear files without giving any prompts to the user. This can be used if you want to run this in multiple servers or if you want to automate it using various methods available.
$TempFileLocation = "$env:windir\Temp","$env:TEMP"
$SoftwareDistributionLocation = "$env:windir\SoftwareDistribution\Download"
$TempFile = Get-ChildItem $TempFileLocation -Recurse
$TempFileCount = ($TempFile).count
if($TempFileCount -eq "0") {
Write-Host "There are no files in the folder $TempFileLocation" -ForegroundColor Green
}
Else {
$TempFile | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Write-Host "Cleared $TempFileCount files in the folder $TempFileLocation" -ForegroundColor Green
}
$SoftwareDistribution = Get-ChildItem $SoftwareDistributionLocation -Recurse
$SoftwareDistributionCount = ($SoftwareDistribution).Count
if($SoftwareDistributionCount -eq "0"){
Write-Host " There are no files in the folder $SoftwareDistributionLocation" -ForegroundColor Green
}
Else
{
$SoftwareDistribution | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Write-Host "Cleared $SoftwareDistributionCount files in the folder $SoftwareDistributionLocation" -ForegroundColor Green
}
Once you run this Script, it deletes the files in the given directories and gives you the information on the files removed. If the file is being used by any process, it will be ignored.
Method 3.
Let’s take it little further.
we will execute this script on multiple computers remotely and clear the temp files on all of them. In this case, I’m going to use the script ./CCleanUp.Ps1 as it doesn’t prompt for user inputs.
1. Make sure you have the PSRemoting is enabled
2. Make sure all the servers that you are trying to run this script are online and in the same domain. If the servers are not domain joined, you will have to add the computer from which you are trying to send commands to the WSMAN Trusted hosts list.
3. Run the below Script in PowerShell session
<#
.Synopsis
Clear space in C: drive
.DESCRIPTION
This Script will help you in clearing some unwanted files in C: drive to make some free space
You have to Navigate to the Script Directory and run the script
.EXAMPLE
./Ccleanup.Ps1
#>
#Script Name : CCleanUp-V1
#Creator : Praveen Kumar
#Date : 18-Sep-2018
#region Method1
#To Execute for a list of Hosts in the same Domain
# Remove the '#' key on the line 6,7 and 8
<#
Param(
$Computername= (Get-Content (Read-Host "Enter the Hosts File path"))
)
#>
#endregion Method2
#region Method2
# To Execute for a Singe / Multiple Hosts by entering the Hosts name or Ip manually
# Remove the '#' key on the line 15 and 16
$Computername = Read-Host "Enter The computer Name".
$Computername=$Computername.split(',')
#endregion Method2
foreach($Computer in $ComputerName) {
$net = Test-Connection $Computer -Quiet -Count 1
If ($net -eq 'True'){
$T1 = ('\\' + $Computer + "\C$\windows\temp")
$T2 = ('\\' + $Computer + "\C$\Users\" + "$env:USERNAME" + "\Appdata\local\temp")
$S = ('\\' + $Computer + "\C$\windows\SoftwareDistribution\Download")
$TempFileLocation = $t1,$t2
$SoftwareDistributionLocation = $S
$TempFile = Get-ChildItem $TempFileLocation -Recurse
$TempFileCount = ($TempFile).count
if($TempFileCount -eq "0") {
Write-Host "There are no files in the folder $TempFileLocation" -ForegroundColor Green
}
Else {
$TempFile | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
}
$SoftwareDistribution = Get-ChildItem $SoftwareDistributionLocation -Recurse
$SoftwareDistributionCount = ($SoftwareDistribution).Count
if($SoftwareDistributionCount -eq "0"){
Write-Host " There are no files in the folder $SoftwareDistributionLocation" -ForegroundColor Green
}
Else
{
$SoftwareDistribution | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
}
#region To display the Disk space on the console
# Remove <# and #> below to run this
$DiskSpace= Get-CimInstance -ClassName win32_logicaldisk -filter "deviceid='c:'" -ComputerName $Computer |
Format-Table @{Name='ComputerName';Expression='PSComputername'},
@{Name='Drive';Expression='Caption'},
@{Name="SizeGB";Expression={($_.Size/1gb) -as [int]}},
@{Name="FreeGB";Expression={[math]::Round($_.Freespace/1gb,2)}},
@{Name="PctFree";Expression={ [math]::Round(($_.freespace/$_.size)*100,2)}} | Out-String
$DiskSpace
#endregion On screen display
#region To Email the Disk Space to team
<#
$DiskSpace | Out-File $Home\Downloads\DiskSpace.txt
$outfile = "$HOME\Downloads\DiskSpace.txt"
Send-MailMessage -From "[email protected]" -To "[email protected]"`
-SmtpServer "Smtp Address" -Subject "Weekly C: Drive CleanUP" -Body "Disk Space" -Attachments $outfile -UseSsl
#>
#endregion email
}
Else {
Write-Host "$Computer is unreachable" -ForegroundColor Red
}
}
This script can be used in multiple ways.
1. Input:
You can Enter the system names manually when you run the script or you can choose to input the file path which contains the Hosts name/Ip address
2. Output:
You can either chose to display the results in the PowerShell Screen or to Send an email message to the intended members who manages the storage space in your environment
By default, this is set to prompt for computer names(Accepts the only comma separated values Ex. Client01, Client02, DC01) and display the C: drive space after clean up in the PowerShell Console. To change this to your needs, follow the steps given in the PowerShell script in the methods.
How to make the best use of this script if you are on a Domain environment?
1. Save this script in one of the domain joined system
2. Get all the computers names in Domain environment and save it in one file
3. Schedule the script once a week using the Windows Task Scheduler
4. Add the Distribution List email or the member’s email address of the team members who manage the storage spaces in the organization.
By following the above steps, you can reduce most of the manual works as I used to do earlier.
Note: if you are not on the domain Joined system, and trying to test this script before you run it in your production environment using your personal email id (Gmail, Yahoo, O365), then you will have to use the Get-Credential cmdlet to pass your credentials. you could save this to a variable and in the Send-MailMessage, Use the -Credential switch to call the variable.
Please comment below and let me know what you guys think on this.
I was very pleased to search out this net-site.I needed to thanks to your time for this glorious learn!! I definitely enjoying each little little bit of it and I have you bookmarked to check out new stuff you blog post.