Need help with Script to rename items in folders

Welcome Forums General PowerShell Q&A Need help with Script to rename items in folders

This topic contains 2 replies, has 3 voices, and was last updated by

11 months, 1 week ago.

  • Author
  • #95652

    Points: 0
    Rank: Member


    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)}


  • #95657

    Points: 5
    Rank: Member

    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
    Rename-Item -Path $OldName -NewName $NewName


  • #95661

    Points: 643
    Helping Hand
    Rank: Major Contributor

    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

The topic ‘Need help with Script to rename items in folders’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort