'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?
Solution 1:[1]
[IO.Directory]::GetCurrentDirectory().split('\\')[-1] will give you the directory you are in.
Solution 2:[2]
Try this
$dirname = resolve-path . | split-path -leaf
Get-ChildItem -Name | Foreach { Rename-Item $_ ( $dirname + $_ ) }
Be careful not to destroy/delete any of your files. No guarantee.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prasanth |
| Solution 2 | JohnB |
