Author Posts

March 11, 2018 at 5:20 pm

Hi,

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:

[PRE]
Get-ChildItem | Get-ChildItem | foreach -Process {
$nr=1
Set-Location -Path (Get-Location).tostring()
Set-Variable -Name "Folder" -Value (Get-Location | Split-Path -Leaf)
Dir | %{Rename-Item $_ -NewName ($Folder + $nr++, $_.extension)}
}
[/PRE]

Thanks

March 11, 2018 at 8:08 pm

Hi Harry,

I think this should work:

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

Kris.

March 11, 2018 at 8:23 pm

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
    }