Delete files based on date selection Powershell script


This is more an Aide-mémoire than a help document, I do not profess to be brilliant at scripting or Powershell, but this works.

It is not time sensitive in the time it takes to run, only about 10 seconds so it is OK for me 🙂

If you get anything from it, good luck to you

# This is used to delete files from a selected folder
# If there are no files with yesterdays date, drop out

# Folder to clean the files
$Clean_Up_Dir = "XXXXXXXXXXXXXXX"
cd $Clean_Up_Dir
$date = Get-Date
#Just get the date
$Yesterday = $date.Date.AddDays(-1)
# Look for files with the .bac extension
$file = dir | Where-Object {$_ -like "*.bac"}
$file_start_date = 0

foreach ($items in $file)
{
#See if there are any file created yesterday, if the are it means that we can delete all of the .bac file
#except yesterdays, if this is null there is no backup and therefore we can not delete anything

 if ($items.LastWriteTime.Date.Date -eq $Yesterday)
 {
 $file_start_date = $items.LastWriteTime.Date.Date
 break
 }
}

if ($file_start_date -eq 0) {}
else
{
# now delete all files that are less that the start date
$file_to_Delete = dir | Where-Object {$_ -like "*.bac" -and $_.LastWriteTime.Date.date -lt $file_start_date}
foreach ($items_delete in $file_to_delete)
 {
 Remove-Item $items_delete.Name -Recurse -Force
 }
}
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s