Saturday, March 23, 2024

Replace characters in folder names using Windows PowerShell

This article describes a method to rename folders by replacing a character with another. In this use case we have a folder full of subfolders which are named in a particular pattern with a date followed by the description of the folder. The words in the folder names are separated by the hyphen ("-') character.  Our objective is to keep the date part intact while replacing all the hyphens after the data with whitespace characters.

The before and after state of the folder names are illustrated in the screenshot below.

Renamed folders with hyphens replaced with whitespace characters

For this example, we consider that our bunch of folders are in a local drive path named "C:\Users\SampleUser\Desktop\2006".

Open the Windows PowerShell and change directory to "C:\Users\SampleUser\Desktop\2006". Next run the following script at the prompt. Remember to set the value of $directoryPath below to the appropriate path according to your situation:

# Set the directory path where you want to rename folders
$directoryPath = "C:\Users\SampleUser\Desktop\2006"

# Get a list of all folders in the specified directory
$folders = Get-ChildItem -Path $directoryPath -Directory

# Loop through each folder
foreach ($folder in $folders) {
    # Check if folder name is longer than 10 characters and contains '-'
    # character at position 11
    if ($folder.Name.Length -ge 11 -and $folder.Name.Substring(10, 1) `
    -eq "-") {
        # Construct the new folder name by replacing '-' with a blank
        # space starting at character number 11
        $newName = $folder.Name.Substring(0, 10) + `
        ($folder.Name.Substring(10) -replace '-', ' ')
       
        # Get the full path of the old and new folder names
        $oldPath = Join-Path -Path $directoryPath -ChildPath $folder.Name
        $newPath = Join-Path -Path $directoryPath -ChildPath $newName
       
        # Rename the folder
        Rename-Item -Path $oldPath -NewName $newName -ErrorAction SilentlyContinue
        Write-Host "Renamed folder: $($folder.Name) to $($newName)"
    }
}

On successful execution of this script, you should see an output like this.

Renamed folder: 2019-01-16-Travel-to-France to 2019-01-16 Travel to France
Renamed folder: 2019-03-07-Meijer to 2019-03-07 Meijer
Renamed folder: 2019-05-04-National-Train-Day to 2019-05-04 National Train Day
Renamed folder: 2019-05-18-Woodland-Park to 2019-05-18 Woodland Park
Renamed folder: 2019-05-26-Maumee-Bay-State-Park to 2019-05-26 Maumee Bay State Park
Renamed folder: 2019-07-05-African-Safari-Wildlife-Park to 2019-07-05 African Safari Wildlife Park

Now you are done.


No comments:

Post a Comment