Global Search / Replace (with Powershell)
Posted By: nicocrm on June 17th, 2009 in Uncategorized
No Gravatar

Had to rename an assembly and was faced with the daunting task of updating a few dozen business rules… I knew I had to do it on the backend as having to click my way through that in App Architect would take a day or more. This is slow but does the trick:

ls -recurse -filter *.xml |% { $text = (get-content $_.FullName) -replace "SourceAssemblyName", "NewAssemblyName"; $text | out-file -encoding utf8 $_.FullName }

Kinda like it better than the old find / grep / sed combo.

There is an alternative that checks if the text was actually modified (otherwise it can append newline to files which sometimes messes things up):

ls -recurse -filter *.xml |% { 
$oldtext = [string]::join([environment]::newline, (get-content $_.FullName));
$text = $oldtext -replace "SourceAssemblyName", "NewAssemblyName"; 
if($text -ne $oldtext) { $text | out-file -encoding utf8 $_.FullName }

Finally I stuck this in my powershell profile (do notepad $profile to bring it up). This lets me use the “ReplText” command without having to retype the whole thing out. It takes the list of files from the input pipeline to be flexible:

# Replace text in every file listed on the input.
# $input: list of file objects (from pipeline)
# $pattern: source pattern (regular expression)
# $replacement: replacement (can have backreferences)
# Usage: dir -recur -filter *.xml | ReplText SourcePattern DestPattern
function ReplText($pattern, $replacement) {
  process {
    $oldtext = [string]::join([environment]::newline, (get-content $_.FullName))
    $newtext = $oldtext -replace $pattern, $replacement
    if($newtext -ne $oldtext) { $newtext | out-file -encoding utf8 $_.FullName }

Leave a Reply