Link to home
Start Free TrialLog in
Avatar of E=mc2
E=mc2Flag for Canada

asked on

Using PowerShell to replace contents of files with specific text

Is it possible to use a script or program to search through a folder and for any files it finds, ie .txt, .ps1, .bat etc... that if it finds specific text it could replace it with other text?

For example for any files that have the phrase "This is a test", to replace that with "This is in production"?

Could PowerShell be used to accomplish this?

Avatar of Dorababu M
Dorababu M
Flag of India image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of E=mc2


Thanks very much, and does this drill down into any folders it might find and the files therein?  Recursive?
Avatar of E=mc2


Thanks, let me give it a try..
Avatar of E=mc2


Should this string:
Get-Childitem -Path "C:\Other" -Recurse -include "*.txt","*.csv" | Select-String "replaced"

be replaced with:  
Get-Childitem -Path "C:\Other" -Recurse -include "*.txt","*.csv" | Select-String "I am replaced"
Hi Yes I do multiple tests that is just to list out what files are replaced
The main code is this
Get-ChildItem $filePath -Recurse -include "*.txt" | ForEach-Object {
# Read the file and use replace()
(Get-Content $_).Replace('Hello','I am replaced') | Set-Content $_

Open in new window