Powershell replace special characters string in all files in directory path

powershellreplacespecial characters

I'm trying to create a 'find and replace' script for the website our company just acquired. Right now, I just want to use it to replace their address and phone number with
ours, but I'll likely need to customize it in the future to replace or update other stuffs.

So far, what I got is:

(Get-Content C:\Scripts\Test.txt) | 
Foreach-Object {$_ -replace "\*", "@"} | 
Set-Content C:\Scripts\Test.txt

which I got from The Scripting Guy 😛

However, I need help customizing it. What I need it to do is:

  • Do it for all files in a directory and all sub-directories, not just one file. The website as far as I can tell is a collection of *.php files
  • Handle special characters that appear in some addresses, like copyrights (©) pipes (|) commas (,) and periods (.)

Here's the exact string I'm trying to replace (as it appears in the .php's):

<p>&#169;Copyright 2012 GSS | 48009 Fremont Blvd., Fremont, CA 94538 USA</p>

Since this could be the first tool in my powershell toolbox, any explaining of what you're adding or changing would greatly help me understand what's going on.

Bonus points:

  • Any way to log which files were 'find-and-replace'ed?

Best Answer

My suggestion would be to use a ForEach loop. I don't see the need for a function in this case, just have the code in your ForEach loop. I would define a string to search for, and a string to replace with. When you perform the replace make sure that it is escaped. Something along these lines:

$TxtToFind = "<p>&#169;Copyright 2012 GSS | 48009 Fremont Blvd., Fremont, CA 94538 USA</p>"
$UpdatedTxt = "<p>&#169;Copyright 2014 | 1234 Somenew St., Houston, TX 77045 USA</p>"
$Logfile = "C:\Temp\FileUpdate.log"
ForEach($File in (GCI C:\WebRoot\ -Recurse)){
    If($File|Select-String $TxtToFind -SimpleMatch -Quiet){
        "Updating lines in $($File.FullName)" |Out-File $Logfile -append
        $File|Select-String $TxtToFind -SimpleMatch -AllMatches|Select -ExpandProperty LineNumber -Unique|Out-File $Logfile -append
        (GC $File.FullName) | %{$_ -replace [RegEx]::Escape($TxtToFind),$UpdatedTxt} | Set-Content $File.Fullname
    }
}