Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files in powershell using the folder name

Using Powershell, I want to rename files in folders by using the name of the folder that the files are in. So in my C:\temp directory, there are 3 folders called 'aaa', 'bbb' and 'ccc'. In each of these folders, there are 3 files called doc1.txt, doc2.txt and doc3.txt. I would like to rename all 9 .txt files to folderName+fileName, so they would be renamed to the following:

aaadoc1.txt
aaadoc2.txt
aaadoc3.txt
bbbdoc1.txt
bbbdoc2.txt
bbbdoc3.txt
cccdoc1.txt
cccdoc2.txt
cccdoc3.txt

Please could anyone point me in the right direction about how to approach this?

like image 910
user1577314 Avatar asked Dec 05 '22 15:12

user1577314


2 Answers

This will rename the files and put an underscore ('_') between the folder name and the file name:

Get-ChildItem C:\temp -Filter *.txt -Recurse | Rename-Item -NewName { $_.Directory.Name+'_'+$_.Name}
like image 107
Shay Levy Avatar answered Jan 08 '23 11:01

Shay Levy


[IO.Directory]::GetCurrentDirectory().split('\\')[-1] will give you the directory you are in.

like image 39
Prasanth Avatar answered Jan 08 '23 11:01

Prasanth