0

I have a set of backup files, like ABC20200216.bak, ABC20200217.bak etc. They all follow this pattern: ABCYYYYMMDD.bak

I have a Windows batch script which deleted all my backup files older than 15 days. This works like magic:

forfiles /p "C:\DB Backup" /m ABC????????.bak /D -15 /C "cmd /c del @path"

But I want to make a change so my backup on each 1st day of the month does not get deleted. So I want to exclude all files ABCYYYYMM01.bak from above script.

I got to know that I need to use Powershell because forfiles does not support regular expressions and I think I'll need regexp to write this.

The max I could do to get a file list using Powershell: powershell "dir 'C:\DB Backup' | ?{ $_.Name -match 'ABC[0-9]{8}.*' } | select Name"

But I don't really know regular expressions, so please help me with a regular expression to exclude files ending in 01.bak.

Plus I don't know how to combine the above Powershell and a delete operation. Can I get some help with this also, please?

  • `.*` at the end should be replaced with `.*$(?<!01\.bak)` – Wiktor Stribiżew Feb 17 '20 at 13:45
  • This help me to get the list of the files the way I want, thanks for that. But there was a second question also: how to combine this list with a delete operation so I can delete the listed files. This second question remained unanswered. – Szilárd Kotta Feb 18 '20 at 23:58
  • 1
    But I finally found the solution: ```powershell "dir 'C:\DB Backup' | ?{ $_.Name -match 'ABC[0-9]{8}.bak$(?<!13.bak)' } | foreach { $_.Delete() }"``` – Szilárd Kotta Feb 19 '20 at 00:06

0 Answers0