How to replace string in files and file and folder names recursively with PowerShell?
11,661
Solution 1
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."
Solution 2
I would go with something like this:
Get-ChildItem $directory -Recurse |
Sort-Object -Descending -Property { $_.FullName } |
ForEach-Object {
if (!$_.PsIsContainer) {
($_|Get-Content) -replace 'A', 'B' | Set-Content $_.FullName
}
$_
} |
Rename-Item { $_.name -replace 'A', 'B' }
The Sort-Object
is there to ensure that first children (subdirs, files) are listed and then directories after them. (12345)
Author by
Martin R-L
Systems tinkerer, tackling complexity in the heart of software and organizations.
Updated on June 15, 2022Comments
-
Martin R-L almost 2 years
With PowerShell (although other suggestions are welcome), how does one recursively loop a directory/folder and
- replace text A with B in all files,
- rename all files so that A is replaced by B, and last
- rename all folders also so that A is replaced by B?
-
Scott Keck-Warren about 13 yearsSo you want one command/function that will replace A with B in file contents, file names, and folder names or are A and B separate in each of those cases?
-
Martin R-L about 13 years"one command/function that will replace A with B in file contents, file names, and folder names" is the case.
-
JasonMArcher about 13 yearsI can tell that is untested, there is no way that would run. :)
-
Emiliano Poggi about 13 yearsIt's little complex, so I would test it as a script.
-
stej about 13 yearsAnd the question is: why? :) As somebody 'around computers' you might know, that "It doesn't work" is as worthy as if you say nothing. Error message is helpful. Otherwise, no need to say "It doesn't work". :)
-
Noah Heldman over 11 yearsThis is awesome. When people realize what this script will allow you to do, you'll get a lot more upvotes... thanks.
-
Jim Wolff over 10 yearsI had some folders and namespaces in code files giving me an issue names like NameSpace.TestConsole (folder) and same goes for some of my namespaces, this script then made a lot of empty files called those names instead, so somehow it also creates new files. is there some way to ensure it only replaces and not creates?
-
Antony about 10 years@BrokenHeart Any reason you want to change my edit?
-
Code Lღver about 10 years@Antony No reason just to make it much better.