Batch rename script

Tagged: 

This topic contains 3 replies, has 4 voices, and was last updated by Profile photo of Olaf Soyk Olaf Soyk 2 weeks, 1 day ago.

  • Author
    Posts
  • #72536
    Profile photo of Steven Fosnot
    Steven Fosnot
    Participant

    Hello all,

    I'm working on a script to rename a large amount of files my team has mislabeled.

    Currently every folder has in example the following.
    ls/dir outputs:
    0.pdf
    00.pdf (file needs to be first)
    1.pdf
    2.pdf
    3.pdf
    4.pdf

    When running: ($nr=1)
    Dir | %{Rename-Item $_ -NewName ('{0}.pdf' -f $nr++)}

    The output is as follows:

    After rename
    1.pdf
    2.pdf (Cover sheet file)
    3.pdf
    4.pdf
    5.pdf
    6.pdf

    I am pretty new to Power Shell and honestly haven't used a CLI in quite some time so I am curious on a method that will sort the 00.pdf to the top and when rename is ran it'll output it to 1.pdf.

  • #72539
    Profile photo of Liam Kemp
    Liam Kemp
    Participant

    Im not sure if there is a way to sort that way. Someone else here may know of a solution.

    If the contents of each folder are always the same order, one method I can think of would be

    Step 1 is fine the way you have it.
    Add a second step to rename 2.pdf to 0.pdf
    Add a third step that is the same as the first

    Liam

  • #72553
    Profile photo of Chris Bakker
    Chris Bakker
    Participant

    This will sort it for you.

    Get-ChildItem *|Sort-Object -Property name

    But in this way, you get in trouble
    The 0.pdf wil come before 00.pdf
    You can use other properties to sort, like access time to.

  • #72554
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant

    It might not be the most sophisticated or elegant way but I guess it does the job:

    $Directory = 'Your Directory with misslabeld files here'
    $Counter = 2
    Get-ChildItem -Path $Directory  -Filter ?.pdf |
        Sort-Object |
            ForEach-Object {
                Rename-Item -Path $_.FullName -NewName ('#####' + $Counter + $_.Extension) 
                $Counter++
            }
    Get-ChildItem -Path $Directory -Filter '00.pdf' | Rename-Item -NewName ('#####1.pdf')
    Get-ChildItem -Path $Directory -Filter '#####?.pdf' | 
        Sort-Object |
        ForEach-Object {
            Rename-Item -Path $_.FullName -NewName (($_.BaseName -replace '#####') + $_.Extension) 
        }

    ... and BTW: if you don't need this on a regular base it would have bin easier to take a file rename batch tool like it is included in some file management tools like FreeCommander

You must be logged in to reply to this topic.