3

At work I've got a Windows directory housing about a thousand folders named

Name, Surname

and need these to be named

Surname, Name

I've done some searching here and on StackEx and haven't found anything that's exactly this with the comma, so I'm here finally to stop lurking and post my own question.

To get ahead of it, I know for a fact there are no extra spaces nor special characters, 3rd names, etc., and I have verified all the folders are just the two names. Any help would be greatly appreciated.

Velvet
  • 1,739

1 Answers1

3

Since you ok'd powershell, here is a powershell script that should do the work for you.
This can also be done in batch fairly easily but I don't suggest it.

I would normally push harder for you to do this yourself.. but this should give you a good launching point for future file processing in powershell.

You can use this concept to process anything you want in any way you want.
Look at where I put the spit line..
that's your before name..

Look at the $newName= line.
that's your after name.

Right there is where you would change the logic of what to find and what to do with it.

param (
    [string]$Path = (Get-Location).Path
)

Get all folders in the specified directory

$folders = Get-ChildItem -Path $Path -Directory

Loop through each folder

foreach ($folder in $folders) { # Split the current folder name by comma $nameParts = $folder.Name.Split(',')

# Check if the folder name has onlyh name, surname
if ($nameParts.Length -eq 2) {
    # Trim and create new name
    $surname = $nameParts[1].Trim()
    $name = $nameParts[0].Trim()
    $newName = "$surname, $name"

    try {
        # Rename the folder
        Rename-Item -Path $folder.FullName -NewName $newName -ErrorAction Stop
        Write-Host "Renamed: '$($folder.Name)' to '$newName'"
    }
    catch {
        Write-Host "Error renaming '$($folder.Name)': $_"
    }
}
else {
    Write-Host "Skipping '$($folder.Name)' - It isn't named X,Y"
}

}