Have folder which has backups of SQL databases with backup date in the name.
e.g. C:\Backup folder.  

Example of backup files:  

archive\_1\_01022022.bak  

archive\_1\_02022022.bak  

archive\_1\_03022022.bak  

archive\_2\_01022022.bak  

archive\_2\_02022022.bak  

archive\_2\_03022022.bak  

archive\_3\_01022022.bak  

archive\_3\_02022022.bak  

archive\_3\_03022022.bak  

I need powershell script which removes all files from this directory but keeps recent ones (e.g. for last 5 days), but at the same time I need to keep at least 3 copies of each database (in case there are no backups done for more than last 5 days).

Below script removes all files and keeps recent ones for last 5 days:

```
$Folder = "C:\Backup"
$CurrentDate = Get-Date 
$DateDel = $CurrentDate.AddDays(-5) 
Get-ChildItem $Folder | Where-Object { $_.LastWriteTime -lt $DateDel } | Remove-Item 

```

Above is wokring fine, but if there are no recent backups for last 10 days and if I run above code then it will remove all files in C:\Backup. For such cases I need to keep at least 3 backup files of each databases.

If I use below code (for example I have 9 different databases), then it do job:

```
$Folder = "C:\Backup"
Get-ChildItem $Folder | ? { -not $_.PSIsContainer } |
Sort-Object -Property LastWriteTime -Descending |  
Select-Object -Skip 27 | 
Remove-Item -Force

```

But implementation is weird. For example if I have backups of 9 databases, then I need to provide "Select-Object -Skip" with value **27** (9 databases x skip 3 files of each database). In case I have more databases or less, then each time I need to adjust this number. How can I make "Select-Object -Skip **3**" static value?