如何使用列表文件重命名文件?

val*_*val 2 powershell rename

我有数百个文件,我想根据相关列表以特定方式重命名它们。我不想重复相同的 cmdlet,如下所示,我想将该 cmdlet 指向几个包含旧名称和新名称的列表文件(如下),例如 old.txt 和 new.txt。如何使用 PowerShell 执行此操作?

例子:

Rename-Item -Path "E:\MyFolder\old1.pdf" -NewName new1.pdf
Rename-Item -Path "E:\MyFolder\old2.tif" -NewName new2.pdf
Rename-Item -Path "E:\MyFolder\old3.pdf" -NewName new3.pdf
Run Code Online (Sandbox Code Playgroud)

列出文件:

旧.txt =

old1.pdf
old2.tif
old3.pdf
Run Code Online (Sandbox Code Playgroud)

新.txt =

new1.pdf
new2.tif
new3.pdf
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 5

只需将两个文件读入两个列表并按如下方式处理它们:

$old = Get-Content 'old.txt'
$new = Get-Content 'new.txt'

Set-Location '$:\MyFolder'

for ($i = 0; $i -lt $old.Count; $i++) {
  Rename-Item $old[$i] $new[$i]
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*sen 5

old.txt为了避免和文件中的条目之间不一致new.txt,您还可以将文件放入 CSV 文件中:

重命名.csv =

old1.pdf,new1.pdf
old2.tif,new2.tif
old3.pdf,new3.pdf
Run Code Online (Sandbox Code Playgroud)

现在您可以使用Import-Csv导入“翻译集”:

old1.pdf,new1.pdf
old2.tif,new2.tif
old3.pdf,new3.pdf
Run Code Online (Sandbox Code Playgroud)