Need help with Script to rename items in folders


I’m working on a script to bulk rename items in several folders.
Basically, I have one master folder, i’ll call ‘a’
inside that folder ‘a’, I have several folders, each with different names, like ‘b’ ‘c’ ‘d’ etc.
Inside of of THOSE folders, I have files, each with unique names.
I want to be able to rename every file in these sub folders, with the name of the folder they are in
ex: I want all files in this ‘b’ subfolder to be name ‘b1.jpg’ ‘b2.jpg’ ‘b3.jpg’ etc. and then i want
all folders in c named ‘c1.jpg’ ‘c2.jpg’ etc.
I have several hundred folders in this master folder ‘a,’ so I want to be able to automate this proccess to into one script that I’ll run in the ‘a’ folder.

Here is code I have:

Get-ChildItem | Get-ChildItem | foreach -Process {
Set-Location -Path (Get-Location).tostring()
Set-Variable -Name “Folder” -Value (Get-Location | Split-Path -Leaf)
Dir | %{Rename-Item $_ -NewName ($Folder + $nr++, $_.extension)}


Hi Harry,

I think this should work:

$Subdirectories = Get-ChildItem -Directory
$SubDirectories | ForEach-Object {
$Files = Get-ChildItem -Path $.FullName -File
$DirectoryName = $
$Counter = 1
$Files | ForEach-Object {
$OldName = $_.FullName
$NewName = “{0}{1}.jpg” -f $DirectoryName, $Counter
Rename-Item -Path $OldName -NewName $NewName


I tried this and it worked in my tests … even for subdirectories

$StartDirectory = ‘D:\sample’
Get-ChildItem -Path $StartDirectory -Recurse -File |
ForEach-Object {
NewFileName = ((Split-Path -Path (Split-Path -Path .FullName -Parent) -Leaf) + '’ + _.Name) Rename-Item -Path _.FullName -NewName $NewFileName