Powershell rename filename by replacing n characters in ascending order

Viewed 294

I've got a number of files in the following format enter image description here

I'd like to replace the 3 characters after 60- in ascending order. I have used the following code to remove the first 28 characters

get-childitem * | rename-item -newname{string.substring(28)}

Then rename using the following

$i = 1

dir | ForEach-Object {$_ | Rename-Item -NewName ('00092-100221-XX-A-233-60-{0:D3} {1}{2}' -f $i++, $.BaseName, $.Extension)}

However I end up losing the original file order. Is there a way I can rename these files by keeping the original file order and also maybe less time consuming?

1 Answers

You can do all in one step, thus preserving the original file order:

$script:i = 1
Get-ChildItem | Rename-Item -NewName {
    '00092-100221-XX-A-233-60-{0:D3}{1}' -f $script:i++, $_.Name.SubString(28)
}

(Note that I excplicitly specified the scope for $i, otherwise the value wouldn't be increased.)

Related