More PowerShell for fun (and profit) – filter files by date

I’ve mentioned this before, but I do adore PowerShell, especially for shortcutting random tasks.

Let’s say you find a folder with a lot of  (say, 90,000) old, useless, unused files in it. But it’s a bit of trouble to sort through those files in the Window and make sure you get the right one. PowerShell provides an easy way to look at and/or delete just the files you want.

Moving around in the PowerShell window

If you’ve used the normal “cmd” command prompt, then you’re probably already familiar with moving around the file structure. But just in case:

  • “cd” means “change directory”
  • cd ..  – Navigate up one folder level
  • cd Log – navigate to a folder named “Log” in my current context
  • c: – change to the C drive
  • cd \\nas\fold\ – change to the shared folder \\nas\fold\

Also: Know that you can type “help”, or “help ” and any command (e.g., “help cd”), and get information back in PowerShell.

posh

Look at specific files

Just like a command prompt, PowerShell lets you look at the contents of a directory, and filter your search using wildcards. For example:

  • dir – show me all the contents of the current folder
  • dir *.txt – show me all the files ending in .txt, in the current folder
  • dir *2016*.txt- show me all the files with “2016” in the name, and ending in .txt, in the current folder

In this way, we can get a list back of just the files we want.

But, what if we want to filter on something other than the name?

Filter by date in PowerShell

PowerShell gives you the where-object cmdlet to filter your results. So here, we’re going to get back all the text files, and then filter by date:

dir *.txt | where-object {$_.LastWriteTime -lt '1/1/2018'}

As usual, we’re going to pick this apart element by element:

  • dir *.txt – let’s see just the files ending in “txt”.
  • | – we “pipe” (pass) those objects along to…
  • where-object { – a filter, which checks …
  • $_.LastWriteTime – each object ($_) for it’s last write time, to see if it’s…
  • -lt ‘1/1/2018’Less Than the date ‘1/1/2018’.
  • } – (End of filter)

So now, we’ll just get those files that were last modified before January 2018.

I have the power, LET ME DELETE

If you’re absolutely sure that’s the set of files you want to delete, you can do so by appending a pipe and the “del” command:

dir *.txt | where-object {$_.LastWriteTime -lt '1/1/2018'} | del

This is very powerful stuff. I encourage you very strongly to play with this in a sandbox where you won’t do much damage if you accidentally run the “del” statement when you meant to just run the “dir” statement.

Anyway, there we go! Another fun and useful application of a little simple PowerShell.