Mahmoud ElMansy: knowledge meant to be free

Replacing Strings in Multiple Files in Folder and SubFolders

This is the second article on windows PowerShell scripting .
Now what we want to do ?
Simply we want to replace certain string by another string value in all files in certain folder and
All sub folders .

$items = Get-ChildItem * -recurse
# enumerate the items array
foreach ($item in $items)
# if the item is a directory, then process it.
if ($item.Attributes -ne "Directory")
(Get-Content $item.FullName ) |
Foreach-Object { $_ -replace 'old', 'new' } |
Set-Content $item.FullName

Or we can use .

Get-ChildItem * -recurse | Where-Object {$_.Attributes -ne "Directory"} |
ForEach-Object { (Get-Content $_) -replace
"old","new" | Set-Content -path $_ }

We can do change to that script to keep backup from that file .

Get-ChildItem * recurse -exclude *.bak | Where-Object {$_.Attributes -ne "Directory"} |
ForEach-Object { Copy-Item $_ "$($_).bak"; (Get-Content $_) -replace
"old","new" | Set-Content -path $_ }

Or to search for specified text.

$txtFiles=get-childitem . *.txt -recurse
foreach ($file in $txtFiles)
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "old", "new"} |
Set-Content $file.PSPath

Here is alink to do that with regular expressions.
A simple PowerShell script to find and replace using regular expressions in multiple files
Hope it helped .