PowerShell Script to Split, Replace and Rename File Names in the Folder Recursively and in Bulk

Important Note: The File renaming in bulk can result in dangerous results in not handled correctly.  This post is ONLY to share my learning’s to serve you as a guidance to build your own scripts for similar requirements. 

Requirement:

I had a folder which contained sub-folders and then files.  The naming convention of file names is “<string> –  <string> – <string>.mp4”.  Out of which the first String is too lengthy and common for all files which I wanted to get rid of it. 

Script:

function Rename-Files ($folder) {

    $files = dir $folder | where {! $_.PsIsContainer}

    # $files = dir $folder | where {! $_.PsIsContainer} | Select-Object -First 1

 

    foreach ($file in $files) {

        $SplitName = $file.Name -Split ” – “

        if ($SplitName.Length -eq 1) { Continue }

        $NewFileName = “”

 

        for($counter = 0; $counter -le ($SplitName.Length 1); $counter++) {

            if ($counter -eq “0” ) {

                Continue

            }

            if ($counter -eq “1” ) {

                $NewFileName += $SplitName[$counter]   

            } else {

                $NewFileName = $NewFileName + ” – “ + $SplitName[$counter]

            }

        }

 

        if ($NewFileName -eq “”) {

            Write-Host “The value of NewFileName is empty [$NewFileName]”

            Continue

        }

        if (Test-Path -path $folder\$NewFileName) {

            Write-Host “The destination path [$folder\$NewFileName] already exists!, skipping renaming!!”

            Continue 

        }

 

        Rename-Item -Path $folder\$file -NewName $NewFileName

        Write-Host “INFO: Successfully renamed file [$folder\$file] to [$NewFileName]”

     }

}

 

$ParentFolder = “G:\1”

$subfolders = dir $ParentFolder -Recurse | where {$_.PsIsContainer}

foreach ($subfolder in $subfolders) {

    $FolderPath = $subfolder.FullName

    Write-Host “Processing Folder [$FolderPath]”

    Rename-Files $FolderPath

}

 

 
PowerShell Script:
 
Final Output:
 
image
 
 
 
 
Advertisements