0

I am able to batch rename files in a working directory by using:

Dir | %{Rename-Item $_ -NewName ("0{0}.wav" -f $nr++)}

However I want the file rename to start at something other than zero. Say 0500, and rename sequentially in order.

Dir | %{Rename-Item $_ -NewName ("0{500}.wav" -f $nr++)}

returns error.

How can I tell rename to start at a number other than 0?

Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26
Fernan
  • 67
  • 2
  • 7
  • simply initialize the counter to the starting number like `$nr = 500`. As aside, by just doing `Dir`, you are playing with fire because that will get you all files and folders in the current directory. Better add the path, a file filter and the `-File` switch to have it only rename .wav files: `(Get-ChildItem -Path '' -Filter '*.wav' -File)` – Theo Dec 28 '20 at 16:06
  • adding `$nr = 500` at the beginning also returns error. I don't mind doing all in `Dir` since I know what is in the working directory and only run it when I need it. Adding the file path can sometimes be long and cumbersome – Fernan Dec 28 '20 at 16:37

1 Answers1

1

You can initialize the counter beforehand to 500. Also, you don't need to use a ForEach-Object loop (%) for this, because the NewName parameter can take a scriptblock.

Important here is that you need to put the Get-ChildItem part in between brackets to let that finish before renaming the items, otherwise you may end up trying to rename files that have already been renamed.

$nr = 500
(Get-ChildItem -Path 'D:\Test' -Filter '*.wav' -File) | Rename-Item -NewName { '{0:D4}{1}' -f ($script:nr++), $_.Extension }
Theo
  • 57,719
  • 8
  • 24
  • 41
  • okay, I thought that the loop would eliminate the need to worry about renaming files that have already been renamed. But in your example you pass a path, i don't want this as I'll already be in the working directory and having to type the dir again can be cumbersome. – Fernan Dec 28 '20 at 16:34
  • @Fernan then leave out the path – Theo Dec 28 '20 at 17:40