Using examples from other sources, I have the following script. It finds the five newest files in Arguement1, matching an string from Arguement2, and deletes the rest.
$Zpath = $args[0] ##write-host $Zpath $Zfile = $args[1] ##write-host $Zfile # Get all the items in Zpath Get-ChildItem -Path $Zpath | # Skip directories Where-Object { -not $_.PsIsContainer } | # Only get files that match certain format Where-Object { $_.Name -match $Zfile } | # Sort them by name, from most recent to oldest Sort-Object -Descending -Property CreationTime | # Keep the first five items Select-Object -Skip 5 | Remove-Item #-WhatIf
The problem is some folders are storing mutliple files in the same folder.
For Example, in the folder we have:
Eggs_20191101
Eggs_20191102
Eggs_20191103
Eggs_20191104
Eggs_20191105
Eggs_20191106
Eggs_20191107
Bacon_20191101
Bacon_20191102
Bacon_20191103
Bacon_20191104
Bacon_20191105
Bacon_20191106
Bacon_20191107
Bacon_20191108
Bacon_20191109
If $Zfile is Eggs, I want to delete all but the five newest Egg files and leave all the Bacon files alone.
-Al H