Search code examples
powershellfilepdfsequentialversion-numbering

Adding sequential numbering to the beginning of file name using Powershell


I have a series of PDF files on my computer that I am trying to rename them using Powershell by adding a sequential number starting at 1000 to the beginning of, preceded by the letter "B".

Current file naming:

FileNameA.pdf
FileNameB.pdf
FileNameC.pdf

What I want:

B1000 - FileNameA.pdf
B1001 - FilenameB.pdf
B1002 - FileNameC.pdf

I tried using the following function to achieve this:

$count=1000; 
dir "C:Temp" | rename-item -newname {"B {0} - {1}" -f $count++,  $_.name}

When I do this it renames all of the files with "B 1000" at the beginning but does not sequentially number them. Can someone help me figure out how to modify this code to achieve this?

Thanks!


Solution

  • The parameter-bound scriptblock {"B {0} - {1}" -f $count++,$_.Name} will run in it's own scope, meaning that any attempt to write to variables (including with ++) will result in PowerShell hiding the variable references behind a local copy - and the value of the original $count variable in the parent scope will therefore remain unaffected.

    Use the script: scope modifier to persist the modification of $count in the parent scope to make it work:

    dir "C:Temp" | rename-item -newname {"B {0} - {1}" -f $script:count++, $_.name}