如何使用 Powershell 递归重命名目录中的文件?

时间:2021-06-14 20:07:47

标签: powershell

我有一个 powershell 脚本,它将“- Confidential”附加到文件的末尾,这些文件与文件名中的字符串“Confidential”不匹配。在目录中运行此脚本时,它可以工作。但是,我也需要它来重命名子文件夹中的所有项目。我怎么能做到这一点?

    Get-ChildItem * -Exclude *Confidential* -Recurse | 
  ForEach {Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }}

感谢大家阅读。

1 个答案:

答案 0 :(得分:1)

您已经接近了,但有一些问题:

  1. Rename-Item 缺少原始文件,因此让我们向其中添加 $_。我们也可以给它 $_.FullName,但我只是将整个对象传递给它。
  2. Rename-Item 被赋予一个没有输入 -NewName 的脚本块,因为您使用了大括号 ({}),因此我们将其更改为常规括号 ({{1} }).
  3. 子文件夹也被重命名,这也会导致其中的文件不被递归(因为它们包含机密),因此我们指定 () 上的 -File 开关以只返回文件。

这让我们想到:

Get-ChildItem

还有一些清理/优化:

  1. Get-ChildItem * -File -Exclude *Confidential* -Recurse | ForEach {Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension )} 中删除通配符 (*)。它已经假定您所在文件夹中的所有项目。
  2. 用引号将字符串括起来。
  3. 在脚本块内添加一些空格并将 Get-ChildItem 别名更改为较短的 ForEach 别名(这只是我个人的喜好)。

最后的结果是这样的:

%

与往常一样,您可以通过在 Get-ChildItem -File -Exclude "*Confidential*" -Recurse | % { Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension ) } 上指定 -WhatIf 来进行试运行,以防出现某些意外行为。

编辑:您实际上可以像这样将 Rename-Item 的输出通过管道传输到 Get-ChildItem 中,而无需 Rename-Item

ForEach-Object