PowerShell Clean Up Tools

021913_2047_WordTest1.pngA few years ago I think I posted some PowerShell clean up tools. These were functions designed to help clear out old files, especially for folders like TEMP. Recently I decided to upgrade them to at least PowerShell 3.0 to take advantage of v3 cmdlets and features. I use these periodically to clean out my temp folders. I should probably set them up as a scheduled job to run monthly, but I haven’t gotten around to that yet. In the mean time, let me show you what I have.

First, I have a function to delete files from a directory that were last modified after a given date.

The function supports -WhatIf so that if I run it, Remove-Item will only show me what it would delete. I use a hashtable to build a set of parameters to splat to Get-ChildItem. I love this technique for building dynamic commands. I use this command on my temp folders to delete files older than the last time the computer booted. My assumption is that anything in TEMP older than the last boot time is fair game for deletion.

If you look at this function, you’ll notice that it only affects files. It leaves folder alone. I suppose I could modify it to remove old folders as well, but there’s a chance the folder might have a newer file somewhere in the hierarchy that shouldn’t be deleted so I decided to simply focus on old files. To clean up folders, I use this:

This command looks for empty folders, or more precisely folders with no files. The function gets all of the top-level folders in the specified path and then searches each folder recursively for any files. If no files are found, the folder is removed.

The two tools are great on their own. To put them to use, I created a small script.

I think of the script as a “canned” PowerShell session. Instead of my typing the commands to clean up a few folders, I simply run the script. I inserted some Write-Host commands so I could know what the script was doing. I clean out all the old files first and then make a second pass to delete any empty folders. I trust it goes without saying that if you want to use these, you have to test in a non-production environment.