The Wayback Machine - https://web.archive.org/web/20240605150138/https://www.geeksforgeeks.org/disk-cleanup-using-powershell-scripts/
Open In App

Disk Cleanup Using Powershell Scripts

Last Updated : 27 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will look at how to delete temporary files, recycle bin data, and run a disc cleanup program in Windows. Windows users sometimes faced low disk space errors with the error “You’re running out of space on this PC. Manage storage to view usage and free up some space.” When Windows prompts low disk space warning messages, we first perform some manual steps to delete temp files which are as follows:

  • Clear temp file with disk cleanup and,
  • Clear other temp files from different locations
    • C:\Windows\Temp
    • C:\Windows\Prefetch
    • C:\Users\*\AppData\Local\Temp

Script to clear Cache and Temporary files on Windows Devices

Manually deleting this much data will take some time and will most likely need a lot of human intervention. Doing the aforementioned procedures manually on a single computer does not take long. But, if you are running 7 to 8 virtual machines with Windows operating system and doing a lot of technical work, there might be performance issues with your machines. Now, doing these manual actions in all the machines takes a long time. To avoid this problem, let’s design a utility. This tool eliminates the need for manual intervention by deleting all data from the aforementioned places, running a disc cleanup tool, and clearing the recycle bin.

Delete Recycle Bin Data

Fetch the path from the system and create a variable $Path and assign the path. Make sure to separate the drive and the path as mentioned below.

  • `Get-ChildItem` will retrieve the specified items and their child’s items from that location.
  • `-ErrorAction` SilentlyContinue will ignore permission security-related issues. The Remove-Item will delete all the data in the present location. The Recurse parameter searches the Path directory its subdirectories and the Force parameter displays hidden files. 
  • `Write-Host` allows you to emit output to the information stream and you can specify the color of text by using the `-ForegroundColor` parameter. 
  • If you want to ignore some files that you do not want to delete, then you can use the `-exclude` parameter.
#1# Removing recycle bin files
# Set the path to the recycle bin on the C drive
$Path = 'C' + ':\$Recycle.Bin'
# Get all items (files and directories) within the recycle bin path, including hidden ones
Get-ChildItem $Path -Force -Recurse -ErrorAction SilentlyContinue |
# Remove the items, excluding any files with the .ini extension
Remove-Item -Recurse -Exclude *.ini -ErrorAction SilentlyContinue
# Display a success message
write-Host "All the necessary data removed from recycle bin successfully" -ForegroundColor Green  

Delete Temp Data

Here, we have specified the paths where the temporary data is present. As you can see, this is explained in detail in the “Delete Recycle Bin data” section.

#2# Remove Temp files from various locations 
write-Host "Erasing temporary files from various locations" -ForegroundColor Yellow  
# Specify the path where temporary files are stored in the Windows Temp folder
$Path1 = 'C' + ':\Windows\Temp' 
# Remove all items (files and directories) from the Windows Temp folder
Get-ChildItem $Path1 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue  
# Specify the path where temporary files are stored in the Windows Prefetch folder
$Path2 = 'C' + ':\Windows\Prefetch' 
# Remove all items (files and directories) from the Windows Prefetch folder
Get-ChildItem $Path2 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue  
# Specify the path where temporary files are stored in the user's AppData\Local\Temp folder
$Path3 = 'C' + ':\Users\*\AppData\Local\Temp' 
# Remove all items (files and directories) from the specified user's Temp folder
Get-ChildItem $Path4 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
# Display a success message
write-Host "removed all the temp files successfully" -ForegroundColor Green 

Note: Please note that the $Path3 has the symbol ‘*’, which denotes ‘All’. $Path3 will give you the error, you need to replace it with your system’s path. 

For Example C:\Users\xyx~1\AppData\Local\Temp

Perform disk Cleanup

The `Cleanmgr` command will remove unused files from the hard drive of your computer. For eg. Temp files, Internet files, downloaded files, and Recycle Bin files can all be cleared using command-line parameters. The Sagerun:1 indicates it will perform disk cleanup only once.

#3# Using Disk cleanup Tool  
# Display a message indicating the usage of the Disk Cleanup tool
write-Host "Using Disk cleanup Tool" -ForegroundColor Yellow  
# Run the Disk Cleanup tool with the specified sagerun parameter
cleanmgr /sagerun:1 | out-Null  
# Emit a beep sound using ASCII code 7
Write-Host "$([char]7)"  
# Pause the script for 5 seconds
Sleep 5  
# Display a success message indicating that Disk Cleanup was successfully done
write-Host "Disk Cleanup Successfully done" -ForegroundColor Green  
# Pause the script for 10 seconds
Sleep 10  

To create the utility, copy the above-mentioned code and save it in the notepad with the extension .ps1 (.ps1 indicates PowerShell file). 

Right-click the file and click “Run with PowerShell”. It will run this utility and will delete the data automatically without any manual intervention.

PowerShell script utility to delete temp files, recycle bin data and perform disk cleanup on Windows

Output file


Similar Reads

How to find the file properties using powershell
PowerShell is a modern command shell that includes the best features of different shells . Unlike the other shells which only accept and return the text but in PowerShell it is different it returns the object in the .NET objects. In this article we will find out certain commands to find the file properties using PowerShell. Find the file properties
2 min read
How to find and replace the content from the file or string using PowerShell
PowerShell is a versatile utility that can manage files and folders in various ways. It gives you access to the system's files and directories and lets you create, copy, delete, move, renames, and examine them. Several useful PowerShell cmdlets can read, write, and replace data in files. In this article, we will see how we can find and replace the
2 min read
How to Install Linux on Windows PowerShell Subsystem?
There are several ways to Install a Linux subsystem on your Windows PC Powershell Environment. It is good for learners, but it is recommended using original Linux OS if you are a developer as the Subsystem lacks the pre-installed Linux tools. Before we begin installing a Linux subsystem, we need to first enable a Windows feature for Subsystems. Ena
2 min read
How to Install PowerShell in Linux?
PowerShell is well-known among Windows administrators. It is a.NET-based task-based command-line shell and scripting language. You can quickly automate tasks for operating system maintenance and much more with PowerShell. PowerShell was once only available for Microsoft Windows. This admin tool, on the other hand, can now be installed and used on L
2 min read
Brutal - Create various Payload, PowerShell Attack, Virus Attack and Launch Listener for a HID
Brutal is an all-in-one toolkit for generating various types of payloads, back-doors, and listeners. It is a Bash Script tool with a human familiar interface. This tool is available on the GitHub platform for free and it is open for contribution. We can generate various types of payloads for getting the passwords from local computers or to get the
2 min read
Create a Log File in PowerShell Script
In this article, we will be discussing a shell script that can be used to report the cumulative connection time for month/year entries found in a system log file. This script can be useful for network administrators or system administrators who need to analyze log files and get an overview of how much time a particular user or IP address has spent
4 min read
Vscan - Vulnerability Scanner Tool Using Nmap And NSE Scripts in Kali Linux
Vscan is a free and open-source tool available on GitHub. Vscan has based nmap scanning techniques, the easiest and useful tool for reconnaissance. Vscan interface is very similar to Metasploit 1 and Metasploit 2. Vscan has its own modules that add additional value to the standard scanner which is nmap. Vscan has NSE scripts that give additional fe
2 min read
Move and Copy different file types in different folders using Shell Scripts
Shell scripts are powerful tools that allow you to automate repetitive tasks and perform complex operations on your file system. One common use case for shell scripts is moving and copying different file types to different folders. In this article, we will explore different examples of shell scripts that can be used to move and copy different file
4 min read
How to Create and Execute Shell Scripts Automatically with WayScript?
The present instructional exercise is a magnificent model for those new to prearrange working in WayScript, as we'll make a Shell script without any preparation. This cycle just requires a moment to do and it's an extraordinary method for getting comfortable with a portion of the devices WayScript offers. Furthermore, assuming that you might want t
2 min read
How to Use Nmap Script Engine (NSE) Scripts in Linux?
Nmap or Network Mapper is an open-source tool that is used to discover hosts and services on a computer network. It is one of the most powerful and flexible port scanners ever built. To install Nmap on any OS such as Ubuntu or Kali Linux you can use the command. It is highly flexible due to the availability of many NSE scripts available. NSE stands
5 min read
Article Tags :