C# ASP.NET SQL SERVER

Powershell replace text in files and recurse subdirectories

I needed to go through every file in a folder and all of its sub directories and open each file and replace a given string. This is what I finally came up with. I'm sure that this can be improved on though...

function ReplaceText($fileInfo)
{
    if( $_.GetType().Name -ne 'FileInfo')
    {
        # i.e. reject DirectoryInfo and other types
         return
    }
    $old = 'my old text'
    $new = 'my new text'
    (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( $_ ) }

» Similar Posts

  1. Powershell Grep
  2. Combine, compress, and update your CSS file in ASP.NET MVC
  3. Is this string numeric in C#?

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=48

» Comments

  1. BobD avatar

    Thank you!! Sovled my problem.

    BobD — January 13, 2010 5:12 PM
  2. Ryan avatar

    It's worth pointing out that the search term in -replace isn't a string, it's an regular expression.

    So to match "[TOKEN]" you need to use the espace (/) character, resulting in "/[TOKEN/]".

    Ryan — January 21, 2010 4:22 AM
  3. guy ellis avatar

    Thanks Ryan - I had not realized that.

    guy ellis — January 21, 2010 11:04 AM

» Leave a Comment