batch renaming files using powershell

房东的猫 提交于 2021-02-17 06:47:08

问题


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?


回答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 }


来源:https://stackoverflow.com/questions/65480249/batch-renaming-files-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!