Author Posts

April 15, 2016 at 7:29 am

Here is the scenario;
I have files named

I want to move the oldest files based on the date that is in the filename to an achive folder. Even though it is now April, the most current file would be legal_tim_03152016.pdf

April 15, 2016 at 10:40 am

Someone might be able to provide a better solution with less code, but this will list the oldest file.

$files = Get-ChildItem -Path \\path\to\files -Filter legal* | 
ForEach-Object {
    [void]($_ -match "(\d{2})(\d{2})(\d{4})")
    $date = "{0}.{1}.{2}" -f $Matches[1],$Matches[2],$Matches[3]
    $_ | Select-Object -Property name,fullname,
    @{n='NewDate';exp={[datetime]$date}}} | 
Sort-Object -Property NewDate -Descending

$files | Select-Object -First 1 -ExpandProperty fullname | 
Move-Item -Destination \\path\to\destination

April 15, 2016 at 11:26 am

That does display a nice list however How do I move the older files and just leave the most current one?

April 15, 2016 at 11:50 am

Try it again. I added the move-item cmdlet.

April 15, 2016 at 12:22 pm

That moved the newest file. I need it to move all the older files and leave the newest one alone.. Here is the other issue.. I want this setup as a scheduled task that will run daily. If I use -First 1 or -Last 1 in the script and there is only one file it will move that and then there will be no file in our master folder.