Move files based on date in filename

This topic contains 4 replies, has 2 voices, and was last updated by  Windows LiveUser151 2 years, 2 months ago.

  • Author
  • #37845

    Windows LiveUser151

    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

  • #37855

    random commandline

    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
  • #37861

    Windows LiveUser151

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

  • #37864

    random commandline

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

  • #37866

    Windows LiveUser151

    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.

You must be logged in to reply to this topic.