PowerShell: Remove Files based on date
I’ve had the need to remove a bunch of differential backup images from my backup server for a short while now – and thought this was the perfect opportunity to crack into powershell. I’m going to post the script and run through the important parts:
dir C:BACKUP -recurse -exclude SERVER1,SERVER2,SERVER3,SERVER4,SERVER1.IMG,SERVER2.IMG,SERVER3.IMG,SERVER4.IMG,FileClean.PS1 | where { ((get-date)-$_.creationTime).days -ge 1} | remove-item -force -recurse
OK, piece by piece!
dir C:BACKUP -recurse
This may look like a normal CMD prompt DIR, however it isn’t. Powershell uses DIR as an alias for Get-ChildItem which has a bunch of switches you can use. In this instance I wanted all files below the C:BACKUP directory so I used -recurse-exclude SERVER1,SERVER2,SERVER3,SERVER4,SERVER1.IMG,SERVER2.IMG,SERVER3.IMG,SERVER4.IMG,FileClean.PS1
I then used the -exclude switch to ensure I don’t also delete the files that I need to keep. In my case I wanted to keep the current folder structure in tact so I excluded the SERVER1,SERVER2 (etc) directories from the Get-ChildItem command. I also didn’t want to remove the original base backup images (just the old differential images) so I’ve excluded them as well SERVER1.IMG,SERVER2.IMG. Finally, I’ve excluded the FileClean.PS1 file as this is the script file that would actually be running on a schedule.where { ((get-date)-$_.creationTime).days -ge 1}
I then piped the output of the Get-ChildItem into the where statement above. This line checks the Get-Date command on every file, and only returns the files that are older than 1 day. This is done by checking the $_.creationTime and only returning files that are greater than 1 (-ge 1)remove-item -force -recurse
Finally, I then pipe the output into the remove-item command. This will automatically delete the files that the first two commands produced. Note that you need to use the -recurse switch otherwise you will receive a bunch of confirmation prompts.
While testing this script I suggest you use the -whatif switch at the end of the remove-item command. This will just output which files the remove-item will be deleting. Its very important you get the correct files the first time, otherwise you may delete all your files! You can now save the script as whatever you like and run it as a scheduled task.
Matt Shadbolt