Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I recently put together a PowerShell script that creates directories named by date in the following format "yyyyMMddHHmm"

What I have been trying to do is figure out how I can go back through and have the script (or just make a new one) automatically delete any directories that are more than three days old. I would like to be able to pull the name of the folder (as in read the date in the format above) and have that be the determining factor but I am unsure as to where I would even start with this one. I guess knowing what the steps are so that I could break it down would be helpful.

Anyone ever try something like this before with PowerShell?

share|improve this question
Do you know about the .AddDay() method on the date objects? It takes negative arguments so you can take tooday's date.(adddays(-3), then use the same code you used to get the yyyyMMddHHmm the first time to get old directories in this script. – uSlackr Sep 15 '11 at 17:43
Thanks! I am reading up on AddDay now and I think this is a good starting point. – Tyson Navarre Sep 15 '11 at 18:03
up vote 2 down vote accepted

How about...

# Find today's date and calculate 3 days ago:
$today = get-date -DisplayHint date
$threeDaysAgo = $today.AddDays(-3)

# Get the folder list
$folders = (gci "c:\somwhere\" | where-object {$_.PSIsContainer -eq $True})

foreach ($f in $folders) {

    # Parse the date from the folder name text and turn into a date object
    $folderdate = get-date -year $f.Name.substring(0,4) -month $f.Name.substring(4,2) -day $f.Name.substring(6,2)

    # compare and do stuff
    if ($folderdate -lt $threeDaysAgo) { 
        write-host $f.Name
        # do delete here if needed

You will need to adjust to taste, and work out if you need directory removal, or content deletion, or more, but that should do for the date part, anyway.

share|improve this answer
Thank you! I added a Remove-Item "c:\somewhere\$f" -recurse and it worked like a charm. I am going to break this down so that I understand all the parts but this should get me going. Thanks again! – Tyson Navarre Sep 16 '11 at 15:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.