How do I recursively rename folders with Powershell? How do I recursively rename folders with Powershell? powershell powershell

How do I recursively rename folders with Powershell?


Here's the solution rbellamy ended up with:

Get-ChildItem $Path -Recurse | %{$_.FullName} |Sort-Object -Property Length -Descending |% {    Write-Host $_    $Item = Get-Item $_    $PathRoot = $Item.FullName | Split-Path    $OldName = $Item.FullName | Split-Path -Leaf    $NewName = $OldName -replace $OldText, $NewText    $NewPath = $PathRoot | Join-Path -ChildPath $NewName    if (!$Item.PSIsContainer -and $Extension -contains $Item.Extension) {        (Get-Content $Item) | % {            #Write-Host $_            $_ -replace $OldText, $NewText        } | Set-Content $Item    }    if ($OldName.Contains($OldText)) {        Rename-Item -Path $Item.FullName -NewName $NewPath    }}


How about this - do a recursive list of the full names, sort it in descending order by the length of the full name, and then run that back through your rename routine.

e.g.

gci <directory> -recurse | foreach {$_.fullname} |  sort -length -desc


Maybe something in this is useful, here's a snippet that recurses and prepends "pre" to a directory structure

$dirs = Get-ChildItem c:/foldertorecurse -rec |  Where-Object {$_.PSIsContainer -eq 1} |  sort fullname -descendingforeach ( $dir in $dirs ) { rename-item -path $dir.fullname -newname ("pre" + $dir.name) }