Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App
Next Article:
Disk Cleanup Using Powershell Scripts
Next article icon

Disk Cleanup Using Powershell Scripts

Last Updated : 27 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
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

Next Article
Disk Cleanup Using Powershell Scripts

S

sonalilotankar
Improve
Article Tags :
  • Linux-Unix
  • Shell Script

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 pro
    2 min read
    Shell Script to Check Disk Space Usage
    Disk usage is a report generated by the Linux system about different disks available or created on the secondary memory. These disks are also known as partitions, they have their isolated filesystem. This facility provides us the measurements of different labels or features like Used space, Free spa
    3 min read
    What is PowerShell? Getting Started with PowerShell
    Windows PowerShell is a powerful, versatile command-line interface (CLI) and scripting environment designed for system administration and automation. Initially released in 2006 by Microsoft, PowerShell has since evolved into a powerful tool used by IT professionals, developers, and sysadmins across
    10 min read
    Menu Driven Shell Script to Check Memory and Disk Usages
    In Linux most of the time, we automate things using the bash scripts. Some script has only one functionality, but some script can do more than one functions. For that, we have to provide the menu to select the option which function should be performed now. This script is called as Menu-Driven Progra
    4 min read
    Implementing Directory Management using Shell Script
    Directory management constitutes the functions dealing with organization and maintenance of various directories. Directories usually contain files of any type, but this may vary between file systems. The content of a directory does not affect the directory object itself. Some of the directory functi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences