I'm trying to work out how to have a script automatically delete a folder based on a date within the folder's name if the folder's name date is OVER 6 years. (Windows)
Folder name format YYYYmmdd
Any assistance would be greatly appreciated !
CodePudding user response:
I'm sure this can be done they way you ask, based on the date in the name.
But in case you can use one based on the last modified date it would be like this:
ForFiles /p "C:\route" /m * /s /d -2190 /c "cmd /c del @path"
2190 would be 6 years in days
CodePudding user response:
You could use regex to match the folder name, convert it to a date and compare.
This is a contrived example but you might get the idea from that.
# Get all of the folders
$folders = Get-ChildItem -Directory
# Loop through the folders and validate the date prefix
$folders | ForEach-Object {
# The replace converts the prefix into a valid dateTime format for comparison
# \d - matches a digit
# {n} - matches the previous token exactly n times
$datePrefix = $_.name -replace '(\d{4})(\d{2})(\d{2})', '$1-$2-$3'
# If the folder name prefix is older than 6 years then it's okay to delete
if ([datetime]$datePrefix -gt (Get-Date).AddYears(-6)) {
'{0}: Folder is older than 6 years. Okay to delete' -f $_.Name
}
}