Windows – PowerShell Delete Directory Based off Date in Name of Folder

powershellscriptingwindowswindows-server-2008

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?

Best Answer

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.