Powershell – How to replace string in files and file and folder names recursively with PowerShell

powershellwindows 7

With PowerShell (although other suggestions are welcome), how does one recursively loop a directory/folder and

  1. replace text A with B in all files,
  2. rename all files so that A is replaced by B, and last
  3. rename all folders also so that A is replaced by B?

Best Answer

With a few requirements refinements, I ended up with this script:

$match = "MyAssembly" 
$replacement = Read-Host "Please enter a solution name"

$files = Get-ChildItem $(get-location) -filter *MyAssembly* -Recurse

$files |
    Sort-Object -Descending -Property { $_.FullName } |
    Rename-Item -newname { $_.name -replace $match, $replacement } -force



$files = Get-ChildItem $(get-location) -include *.cs, *.csproj, *.sln -Recurse 

foreach($file in $files) 
{ 
    ((Get-Content $file.fullname) -creplace $match, $replacement) | set-content $file.fullname 
}

read-host -prompt "Done! Press any key to close."