• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 833
  • Last Modified:

Using Powershell to Search & Replace

I'm helping the web guy replace some lines in files that are on our web server and I thought I found a quick way to complete it.  I borrowed the below code from somewhere on the internet, and it works well for finding and replacing simple text, but it won't find the string I've filled in (behind the $old and $new.)  I don't use Powershell often, so I'm sure it's just some special characters that need to be escaped out, but I'm not sure.  Any help would be greatly appreciated.

function ReplaceText($fileInfo)
{
    if( $_.GetType().Name -ne 'FileInfo')
    {
        # i.e. reject DirectoryInfo and other types
         return
    }
    $old = 'require($_SERVER["DOCUMENT_ROOT"] . "/html_temp_sets/pageset.php");'
    $new = 'require("../../includes/php/pageset.php");'
    (Get-Content $fileInfo.FullName) | % {$_ -replace $old, $new} | Set-Content -path $fileInfo.FullName
    "Processed: " + $fileInfo.FullName
}

$loc = 'c:\my file\location'
cd $loc
$files = Get-ChildItem . -recurse

$files | % { ReplaceText( $_ ) }
0
Allen
Asked:
Allen
1 Solution
 
Chris DentPowerShell DeveloperCommented:

-Replace uses a Regular Expression for the search value. That can give you some really odd results if you include special characters in your $Old value.

Rather than worrying too much about it you can call the Replace Method on the string (rather than using -Replace). You lose the power of the Regular Expression search, but you don't have to worry about special characters in the strings.

e.g.

...
{ $_.Replace($Old, $New) }
...

Chris
0
 
AllenAuthor Commented:
That did the trick!  Thank you very much!
0

Featured Post

A Cyber Security RX to Protect Your Organization

Join us on December 13th for a webinar to learn how medical providers can defend against malware with a cyber security "Rx" that supports a healthy technology adoption plan for every healthcare organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now