George Meshin
George Meshin

Reputation: 15

Copy the first file of month

I have a backup folder and I need to copy the first file of month from it for each month. The problem is that in each month the first files have different date (not 0101, 0102,0103 etc, but 0401, 0302, 0503 etc(ddmm)).

Is it possible in powershell to set a condition for the file name such as: if the file name contains in this place (month) the 01, then copy the file, which name contains in this place (day) a number that is as close as possible to 1?

File name type: filebackup02012019.

Thank you in advance!

Upvotes: 0

Views: 235

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Group the files by month

Get-ChildItem | Group-Object {$_.BaseName -replace '.*\d{2}(\d{2})\d{4}', '$1'}

Then sort each group by date in descending order and pick the first result

... | ForEach-Object {
    $_.Group |
        Sort-Object {$_.BaseName -replace '.*(\d{2})(\d{2})(\d{4})', '$3$2$1'} -Descending |
        Select-Object -First 1
}

Upvotes: 1

Related Questions