Tuesday, May 28, 2013

How To: Replace a string in all files in a directory with Powershell

If we need to replace some string from all .txt files placed under C:\Myscript directory, below are the steps 1) Copy below script and paste in .ps1 file lets take Test.ps1 as example
param($R,$W,$Ext) ##Replaces all the occurrences in the Views folder## foreach ($f in Get-ChildItem -path "C:\MyScripts\" -Filter *.$Ext | sort-object) {(Get-Content $f.fullname) | Foreach-Object {$_ -replace "$R", "$W"} | Set-Content $f.fullname}
2) Go to Run 3) type Powershell 4) execute Test.ps1 "X" "Y" "txt" Test.ps1 will search all .txt files under C:\myscript folder and replace All X with Y. Thanks Pawan