我有一个 powershell 脚本,它将“- Confidential”附加到文件的末尾,这些文件与文件名中的字符串“Confidential”不匹配。在目录中运行此脚本时,它可以工作。但是,我也需要它来重命名子文件夹中的所有项目。我怎么能做到这一点?
Get-ChildItem * -Exclude *Confidential* -Recurse |
ForEach {Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }}
感谢大家阅读。
答案 0 :(得分:1)
您已经接近了,但有一些问题:
Rename-Item
缺少原始文件,因此让我们向其中添加 $_
。我们也可以给它 $_.FullName
,但我只是将整个对象传递给它。Rename-Item
被赋予一个没有输入 -NewName
的脚本块,因为您使用了大括号 ({}
),因此我们将其更改为常规括号 ({{1} }).()
上的 -File
开关以只返回文件。这让我们想到:
Get-ChildItem
还有一些清理/优化:
Get-ChildItem * -File -Exclude *Confidential* -Recurse |
ForEach {Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension )}
中删除通配符 (*
)。它已经假定您所在文件夹中的所有项目。Get-ChildItem
别名更改为较短的 ForEach
别名(这只是我个人的喜好)。最后的结果是这样的:
%
与往常一样,您可以通过在 Get-ChildItem -File -Exclude "*Confidential*" -Recurse |
% { Rename-Item $_ -NewName ( $_.BaseName + " - Confidential" + $_.Extension ) }
上指定 -WhatIf
来进行试运行,以防出现某些意外行为。
编辑:您实际上可以像这样将 Rename-Item
的输出通过管道传输到 Get-ChildItem
中,而无需 Rename-Item
:
ForEach-Object