Skip to main content

Deleting old files with Powershell

Practical Powershell. Today we will be using Powershell to help you with day-to-day tasks. We are going to explore how to create a Powershell script to delete old files on your hard drive.

Like I have said before, I enjoy Powershell and like how it gives me more control over my computer, particularly how it makes mundane tasks a lot more simple [and fast] for me to do. The good news is that if you don't have a lot of experience with Powershell, it is quite easy to extend and build new features using the language.

Powershell logo (credits to https://powershellnews.podbean.com/)
Powershell (not the official logo)

Let's get started.

Writing the script

In order for us to delete all of the old files from our hard drive, we need to be able to somehow find all these old files. A better question to ask would be; "what qualifies a file as old?" For the purposes of this example, let's assume that any file that has not been modified in the past 3 years be marked as "old" and should be deleted. Great - now how do we delete these files in Powershell?

We will be making use of cmdlets, particularly the Get-ChildItem cmdlet. The Get-ChildItem cmdlet ("command-let") returns child items from a given location. We are going to use this to return all of the files on our hard drive. Assuming you have a C:\ drive like most (if you are on Windows), run the following command in Powershell:
Get-ChildItem -Path C:
You should have a list of files and folders that are in your C:\ directory.

The results of a Powershell command
Getting items in your C:\ drive

Great, but how do we get all of the files on our hard drive? We can do that with the -Recurse flag (Microsoft calls these parameters but it is very common in software development to call these flags). Try running the following command:
Get-ChildItem -Path C: -Recurse
Very likely, you will have a lot of files that will be printed after running this command. You can wait to view all of these files, which will take a very long time, or you can hit ctrl + c to stop the command from executing. But, you might have multiple users on your machine, what if you want to search for the files of the currently logged-in user? You would have to change your command to something like this:
Get-ChildItem -Path C:\Users\[username] -Recurse
Replacing [username] with the name of your user account on your computer.

This isn't good enough, we don't ever want to hardcode values, even in our scripts. I would think (hope) that we could get the value of our user folder programmatically, don't you? The good news is, we can with environment variables. In order to access an environment variable in Powershell, all we need to type is $env:[environmentvariablename]. The environment variable that holds the user folder is USERPROFILE, so to return the value of our user directory, we can execute this in Powershell:
$env:USERPROFILE
Powershell, returning environment variable values
The current user's directory

You may be asking, how does that command work? Therein lies some complexity that requires explanation:
  1. Powershell uses the colon character to denote drives. For comparison, this is how Powershell knows to look in the C:\ drive.
  2. Windows actually stores environment variables in it's own drive named Env.
  3. Powershell makes available the variable $env as an alias to the Env:\ drive.
In fact, you can list out all environment variables in Powershell by executing Get-ChildItem Env:!

Let's now pull in all files for our currently logged-in user:
Get-ChildItem -Path $env:USERPROFILE -Recurse
The reason we are using $env: instead of Env: is that $env will return for us the string value of the environment variable, instead of Env:, which returns a hash table entry for the given environment variable.

There is still room for improvement, however. I am still getting files of every single extension returned, it would be great to filter the file extensions and only delete files of types that I actively use. Fortunately, there is a built-in flag in the Get-ChildItem cmdlet that allows me to do that, -Include. See the example below:
Get-ChildItem -Path $env:USERPROFILE -Recurse -Include *.png, *.docx
I can use the -Include flag to only include files that match a given extension. I can also include multiple extensions by separating them with a comma.

How do we look at old files?

I hope you didn't forget, but we still need to only pull the files that haven't been modified in over 3 years to be deleted. In order for us to do that, we need to know when each file was modified. We haven't yet seen the properties on files in Powershell, and for us to see them, we will have to use Format-List. Format-List will allow us to see all of the properties on a given file (including last modified date).

In order to use Format-List, we will have to pipe the output from Get-ChildItem to Format-List. Please see here if you want a primer on pipes. To see the output of Format-List, we can run the following command (be sure to abord the command with ctrl + c to stop it and view the output):
Get-ChildItem -Path $env:USERPROFILE -Recurse -Include *.png, *.docx | Format-List *
From this output, we can see that there is a property named LastWriteTime, which is essentially our "last modified date" that we need to check against.

Output of the Format-List cmdlet
Look at all those details

In order to select all of the files whose LastWriteTime is older than 3 years, we can use the Where-Object command to filter the files like so:
Get-ChildItem -Path $env:USERPROFILE -Recurse -Include *.png, *.docx | Where-Object LastWriteTime -LT (Get-Date).AddYears(-3)
We compare the LastWriteTime to be less than 3 years ago using the Where-Object cmdlet.


Removing the files

Pipe that command into Remove-Item and you are set!
Get-ChildItem -Path $env:USERPROFILE -Recurse -Include *.png, *.docx | Where-Object LastWriteTime -LE (Get-Date).AddYears(-3) | Remove-Item

To be continued

We will explore later how we can combine our script with Task Scheduler to automate our script. Stay tuned.

Comments

  1. i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    ReplyDelete

Post a Comment

Popular posts from this blog

UI redesigns are mostly a waste of time

To preface the article, I primarily work on, and prefer, back-end code. I've been involved in both web and software development for over 4 years now and worked with many front-end and back-end frameworks. New Twitter UI Before all of the UI designers that read this go out and riot and champion against me for saying UI redesigns are a waste of time, let me say that I do value design . I think at the bare minimum, a product or website needs to be usable , and if you possess a good eye and steady hand , you should feel compelled to create something that looks pleasing. David Just stop redesigning the UI all the time . UI redesigns, in my opinion, are a waste of time 95% of the time. Let me explain further. No one cares Come see our fresh new look ! What about our new  material design , come see! I'm sorry, but besides fixing the UI where it impacts the usability of your application, no one is raving about how a redesign makes the application any better.

[Fix] - ASUS PCE-AC68 adapter (no internet)

There seem to be a lot of problems with this adapter, even with such strong performance . Why so many issues? I'm not quite sure, but I needed to find a fix because I kept on losing wifi. The ASUS PCE-AC68 The fix Keeping it short - this is how I fixed the issue: Downloaded the driver for my OS from ASUS's support page -  https://www.asus.com/us/Networking/PCEAC68/HelpDesk_Download/ (in my case it was Windows 10 64-bit). Open Device Manager by holding the Windows key and pressing R, then typing "devmgmt.msc" and hitting Enter. (Don't worry, this isn't a scam . We are simply opening Window's Device Manager through the Microsoft Management Console snap-in .) Navigate to the yellow warning sign sitting under Network adapters and right click it. Select Update driver . Select Browse my computer for driver software  and choose the following path of the OS that you have installed on your computer. (The path for the driver on my computer was C

Logging into a website with Powershell

Powershell is great, and it's lately been my go-to shell while I'm working on Windows. Sorry command prompt I really don't do a lot of work in the shell, but I do like to play with low-level interfaces from time to time. The article is about Linux shells, but goes into good explanation about what a shell is if you don't know. Log into a website Today, I wanted to do something that I have never really tried before and that is logging into a website using Powershell . The concepts behind this are quite simple really, as Powershell has support to send HTTP requests  and that's usually all we need, unless the server has CSRF protections in place (which it should). We are going to attempt  to log in to my favorite website for buying socks, Absolute Socks : Is that a turkey?! In order to do that, we need to have a login. So if you don't already have an account on www.absolutesocks.com , go make one now. Viewing the login request On websites,