Move files based on date in filename

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Windows LiveUser151 Windows LiveUser151 5 months, 2 weeks ago.

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #37845

    Here is the scenario;
    I have files named
    legal_tim_0115/2016.pdf
    legal_tim_02232016.pdf
    legal_tim_03152016.pdf

    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
    Profile photo of random commandline
    random commandline
    Participant

    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

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

    #37864
    Profile photo of random commandline
    random commandline
    Participant

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

    #37866

    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.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.