Rename-item in multiple subfolders

2019-09-15 04:45发布

问题:

I have a piece of software which looks for a files named "report.txt". However, the text files aren't all named report.txt and I have hundreds of sub folders to go through.

Scenario:

J:\Logs
26-09-16\log.txt
27-09-16\report270916.txt
28-09-16\report902916.txt

I want to search through all the sub folders for the files *.txt in J:\logs and rename them to report.txt.

I tried this but it complained about the path:

Get-ChildItem * |
Where-Object { !$_.PSIsContainer } |
Rename-Item -NewName { $_.name -replace '_$.txt ','report.txt' }

回答1:

Get-ChildItem * will get your current path, so in instead let's use the define the path you want Get-ChildItem -Path "J:\Logs" and add recurse because we want the files in all the subfolders.

Then let's add use the include and file parameter of Get-ChildItem rather than Where-Object

Then if we pipe that to ForEach, we can use the Rename-Item on each object, where the object to rename will be $_ and the NewName will be report.txt.

Get-ChildItem -Path "J:\Logs" -include "*.txt" -file -recurse | ForEach {Rename-Item -Path $_ -NewName "report.txt"}

We can trim this down a bit in one-liner fashion with a couple aliases and rely on position rather than listing each parameter

gci "J:\Logs" -include "*.txt" -file -recurse | % {ren $_ "report.txt"}