重命名批量文件

时间:2016-09-18 12:10:03

标签: powershell

我想使用PowerShell批量重命名文件,例如:

  • my-file-name-photo.jpgmy-file-name-new-photo.jpg
  • this file name photo.jpgthis file name new photo.jpg
  • this is best image.jpgthis is best new image.jpg

“新”是针对前者的。我希望在文件名中添加单词。

2 个答案:

答案 0 :(得分:1)

使用Get-ChildItem cmdlet检索文件并将其传递到Rename-Item cmdlet。使用空格的示例(根据您的评论中的要求):

Get-ChildItem 'c:\tmp' | 
    Rename-Item -NewName {('{0} new{1}' -f $_.BaseName, $_.Extension) }

答案 1 :(得分:1)

$names = 'my-file-name-photo.jpg',    #'my-file-name-new-photo.jpg'
         'this file name photo.jpg',  #'this file name new photo.jpg
         'this is best image.jpg'     #this is best new image.jpg

$names | ForEach { $_ -replace '(.)(photo|image)', '$1new$1$2' }

这将执行您描述的字符串替换。它会查找任何字符(空格或短划线),然后是'照片'或'图像'并且放置新的'在前面,使用相同的分隔符。

Rename-Item(Martin Brandl的回答)一起使用来重命名文件,例如在PowerShell提示符下:

cd c:\users\yourname\Documents\Photos
Get-ChildItem | Rename-Item -NewName { $_.Name -replace '(.)(photo|image)', '$1new$1$2' }