Great Technology Talk

Thursday, June 27, 2013

Rename folders recursively using PowerShell

When recursively renaming folders in PowerShell you have to start with the deepest folders first. This can be a challenge...
This script replaces "-" with "_" in folder names recursively.
 I use this for my Photo storage folders.

$dirs = gci -Path "F:\_ImageDrop" -Recurse |Where-Object {$_.PSIsContainer -eq 1}| %{$_.FullName} | Sort-Object -Property length -Descending  
foreach ( $dir in $dirs ) {
    $item = Get-Item $dir
    $oldpath = $($item.fullname)
    $oldname = $($item.fullname | split-path -leaf)
    $newname = $($oldname) -replace "-","_"
    write-host Checking Path: $oldpath
    if (!$oldname.contains($newname)) {Write-Host Renaming $oldname to $newname; Rename-Item -Path $oldpath -NewName $newname}
    }

Labels: