Shell – Add Increasing Numbers to Beginning of FileName in Powershell

powershell

I have a set of files in a folder, all pdfs. There is no uniform name to the documents, but I would like each one to be proceeded by a number, followed by an underscore, then "TAB." In other words, I want it to look like this:

1.01_TAB "fsfsdFSDF"

2.01_TAB "sjfsdjfsd"

etc.

Can someone help with this? Here's what I have so far:

$x=1

Dir *.pdf | Rename-Item -NewName { $x+ $.BaseName+ $.Extension; -f $x++}

Best Answer

I;m guessing you didn't actually want quotes around the original filenames. Try the following code. In my testing, $i won't increment inside the 'Newname' scriptblock unless it's a reference variable. With the -WhatIf parameter, you can safely test the code:

$i = [ref]1
gci *.pdf | rename-item -NewName {'{0}.01_TAB {1}' -f $i.value++, $_.Name} -whatif

Keith

Related Question