如何在powershell中递归地附加到文件名?

问题描述 投票:1回答:1

我在文件夹/它们的子文件夹中有多个.txt文件。

我想在其文件名后附加_old。

我尝试过:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '.txt','_old.txt' }

这导致:

  1. 某些文件已正确更新
  2. 某些文件更新不正确-他们两次被_old损坏-例如:.._old_old.txt
  3. 几乎没有错误:Rename-Item : Source and destination path must be different.
powershell
1个回答
1
投票

为了防止已经重命名的文件意外地reentering枚举并因此被重命名了[[multiple次,请将Get-ChildItem调用包含在()中,即grouping operator,以确保收集了所有输出first,然后通过管道发送结果:

(Get-ChildItem -Recurse) | Rename-Item -NewName {$_.name -replace '\.txt$','_old.txt' }
但是,我建议按以下方式优化您的命令:

Get-ChildItem -Recurse -File *.txt | Rename-Item -NewName { $_.BaseName + '_old' + $_.Extension }

© www.soinside.com 2019 - 2024. All rights reserved.