Renaming files in powershell using the folder name

2020-06-06 02:09发布

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?

3条回答
We Are One
2楼-- · 2020-06-06 02:29

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

查看更多
放我归山
3楼-- · 2020-06-06 02:47

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}
查看更多
可以哭但决不认输i
4楼-- · 2020-06-06 02:50

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.

查看更多
登录 后发表回答