Batch rename script

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.

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

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.

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

try Krojam Soft Batch Rename program

I guess you can first:

mv 00.pdf -1.pdf

but won’t there be errors because often the new filename already exists (unless you sent the results to another folder or do it backwards)?

Another way to do it with a script block:

Dir | Rename-Item -NewName { "$([int]$_.basename + 1).pdf" }

Apparently, any parameter that can take pipe input, can accept a script block.

echo hi | echo -inputobject { $_ }

hi