Archive

Archive for October, 2012

Replace characters in file names

October 17, 2012 2 comments

A colleague of mine needed to migrate a file share with a lot of documents to SharePoint. During this process he ran into a problem. Lots of documents had a ‘&‘ character in the name, which is not allowed on SharePoint. During the large amount of files and the nesting of a large amount of folders, it was too much work to manually find all the files with this character and change their names. To make it a little bit easier, I’ve created the PowerShell script below. It might be useful to others as well J.

# Provide the name of the root folder
$folderWithFiles  = “C:\Temp”

# Provide the character to replace
$charactersToReplace = “&”

# Provide the character to replace with
$charactersToReplaceWith = “_”

# When setting this value too false, no updates will be made, but the script will display the files containing the $charactersToReplace
$performUpdate = $false

# No changes need to be made below this
$filter = “*$charactersToReplace*”

function PerformReplace() {
    $replacesMade = $false
    get-childitem -recurse $folderWithFiles -Filter $filter | ForEach-Object {
        if($performUpdate) {
            rename-item $_.FullName -newname $_.Name.Replace($charactersToReplace,$charactersToReplaceWith)
            Write-Host “The following file is renamed: “ $_.FullName -ForegroundColor DarkGreen
            $replacesMade = $true
        }
        else {

            Write-Host “The following file should be renamed: ” $_.FullName -ForegroundColor DarkRed
        }
    }
    $replacesMade 

}

# Keep running the script until no more changes have been made. When a replacement has been made
# in a folder name, the containing files will not be updated until the next loop.
function PerformReplaceUntilNoFilesFound() {
    $replacesMade = $true
    do {
        $replacesMade = PerformReplace
    }
    while ($replacesMade -eq $true)
}

PerformReplaceUntilNoFilesFound

Advertisements
Categories: PowerShell
Ben Prins

What I want to remember about SharePoint

blog.frederique.harmsze.nl

my world of work and user experiences

Bram de Jager - Coder, Speaker, Author

Office 365, SharePoint and Azure