Powershell Delete files older than X days, but keep at least 1

I currently backup my switch/router configs automatically every time we write changes... This is done by through ftp sending a text file to a folder.

I am trying to write a script that would delete all files in a directory older than 15 days. However I want to keep the latest file for each device even if it is older than 15 days.

The format of the file naming is as follows: Latest File name is Hostname-Config-Change.txt when it is overwritten by a newer change it gets renamed to: Hostname-Config-Change_MM-DD-YY_HH-MM-SS_Time.txt

I think the easiest way to accomplish this is to delete all files older than 15 days with the date and time in the name. I have no idea how to approach this and although I have found ways to do either of these, I have not found a way to do both.

Thank you in advance for any assistance you could provide.

This is my code so far. I am now to powershell, so any advice would be appreciated.

#Set Variables
# Get current date/time then subtract days to keep files.
$limit = (Get-Date).AddDays(-15)
#Set path of Files to be scanned & deleted
$path = "Directory to Files"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
#End of Script
4

1 Answer

Just for easy of use for everyone that might follow. Using the above responses, I was able to figure out how to use regex to just look at any file with a date in the file name that is older than X amount of days. The latest file does not contain a date in the filename so it worked for me. Be warned you will have to adjust the regex depending on the syntax of the date.

#Set Variables
# Get current date/time then subtract days to keep files.
$limit = (Get-Date).AddDays(-15)
#Set path of Files to be scanned & deleted
$path = "D:\BACKUPS\ConfigChange"
# Delete files older than the $limit and matching the dates in the file name.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.BaseName -match '(\d{2})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})' -and $_.CreationTime -lt $limit } | Remove-Item -Force
#End of Script

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like