Tag Archives: find

How to Search Files Recursivly and Replace content in files

I was tasked to search many files in a directory structure and find content in each file and replace that content. The directory has MANY types of files in it so I had to search for a certain type of file, then search inside that file and replace a string if found.

So, I did this:

Get-ChildItem | ForEach-Object Get-Content -replace and then Set-Content

change *File.Type* with the filetype you want to search for. It could be a *.log or a *.bak

Change string1 to what you’re looking for and string2 to what you want to change it to.

NOTE: This code will save the file with a new date even if it doesn’t replace the string. One minor issue that you must be aware of because if you later want to search for all old files and delete them, it wont find old ones that you’ve touched with this script because of the date change. I’m working on a new version that only saves the file if the string is found in it. Feel free to comment if you got the answer to this 🙂

Here is the code:

Get-ChildItem -include *File.Type* -Recurse | ForEach-Object { ( Get-Content -Path $_.FullName ) -replace 'string1', 'string2' | set-content $_.fullname }