Advice for Creating a PowerShell Script to Delete Old Backup Files

0
13
Asked By TechieTurtle73 On

Hey everyone! I'm a beginner in PowerShell scripting and have done some basic tasks in the past. Right now, I need to create a script that deletes .bak files from a server while keeping one recent file in each subdirectory as a backup. Specifically, I need to keep one file from the last 90 days and another from the last 180 days, but I'm hitting some roadblocks. I have a rough script started and would appreciate any guidance on how to improve it. Here's what I have so far:

```powershell
$DeleteDate = Get-Date.AddDays(-30)

if {
Get-ChildItem path -Recurse | Where-Object {$_.PSIsContainer -and (Get-ChildItem $_.FullName | Where-Object {!$_.PSIsContainer}).Count -gt 1}
Get-ChildItem 'path' -Recurse -Force | Where-Object {$_.PSIsContainer -eq $false -and $_.Extension -match 'bak'} | Where-Object {$_.LastWriteTime -lt $DeleteDate} | Remove-Item -Force
}
else {
# end program line
}
```

I was also thinking about how to maintain files in those specific date ranges, but I'm not sure how to structure the logic so the script doesn't just delete everything over 30 days. I just want to keep the oldest files that meet the age criteria. Any tips or example scripts would be super helpful. Thanks a bunch!

3 Answers

Answered By LogMaster99 On

Don't forget to add some logging when you delete files! It can save you from a potential disaster later on. Just a simple log can help track what was deleted.

Answered By BackupGuru91 On

If those backups are critical, I recommend setting up a proper backup process instead of this script. It will save you a lot of hassle and ensure you have reliable copies of your files.

Answered By ScriptyMcScriptface On

You might want to create an array of all the .bak files and identify the most recent one in each directory. Just grab the last modified date close to the 90 and 180-day marks. It'll simplify your logic a lot!

NewbieCoder2024 -

That's a great idea! I’m really new to scripting, so I'll give that a shot. Thanks for the suggestion!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.