简体   繁体   English

Powershell 更改文件夹内一个子文件夹(副文件夹名称)中的部分文件名

[英]Powershell change part of file names within one subfolder( byfolder name) within a folder

I'd like to bulk rename files filtered by folder name.我想批量重命名按文件夹名称过滤的文件。

I have used the following code我使用了以下代码

dir .\* -include "*Plantegninger*"-recurse| Rename-Item -NewName {$_.name -replace "-00K-","-00U-"}

In the above code the files I want to replace, part of name, are in subfolder named "Plantegninger" I want to change -00K- to -00U- I have many sub folders with this name within sub folders in my main folder.在上面的代码中,我要替换的文件(名称的一部分)位于名为“Plantegninger”的子文件夹中,我想将 -00K- 更改为 -00U- 我的主文件夹中的子文件夹中有许多具有此名称的子文件夹。 Therefore I'm trying to do this recursively.因此,我试图递归地执行此操作。 But I believe this is filtering by filename and not sub folder name.但我相信这是按文件名而不是子文件夹名过滤。 How do I filter by sub folder name, then change file name only within sub folders of that particular name?如何按子文件夹名称过滤,然后仅在该特定名称的子文件夹内更改文件名? Also can I filter by sub folder name and then by filename within that sub folder?我也可以按子文件夹名称然后按该子文件夹中的文件名过滤吗?

If you split the operation into two distinct steps it becomes easier to reason about:如果将操作拆分为两个不同的步骤,则更容易推理:

  1. Enumerate all subfolders with the given name枚举具有给定名称的所有子文件夹
  2. Rename relevant files in each subfolder重命名每个子文件夹中的相关文件
# enumerate relevant sub folders
$subfolders = Get-ChildItem -Filter '*Plantegninger*' -Directory -Recurse

# rename files in subfolders 
$subfolders |Get-ChildItem -File |Rename-Item -NewName {$_.Name -replace "-00K-","-00U-"}

Once you have it working as intended, you can always combine the statements to a single pipeline again (if desired - I personally find it more readable with separate statements):一旦你让它按预期工作,你总是可以再次将语句组合到单个管道中(如果需要 - 我个人认为使用单独的语句更易读):

Get-ChildItem -Filter '*Plantegninger*' -Directory -Recurse |Get-ChildItem -File |Rename-Item -NewName {$_.Name -replace "-00K-","-00U-"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM