Developing on Staxmanade

Massive Search & Replace Among Files Checked-in to TFS

This post is a note to myself, as the two outlined below contain code/commands I've done (wished I could have done automatically in the past) that I want to save for reference later.

I spent the last (almost full year) taking baby steps in an effort to make our logic layer a tiny smidgen eency weency bit more testable. Trust me, trying to replace an everything's a Singleton architecture is no easy task. I won't go into my strong dislike for Singletons – take a look at Singletons are Evil. I've slowly worn the team down into an agreement that we will not propagate any more Singletons in the project. They've given me a new saying "Read my lips. NO NEW SINGLETONS!".

PowerShell assisted regular expression search and replace.

In my case, the specific regular expression needed to find


and replace it with


Below is the PowerShell script I used.

# define the find and replacement regular expressions.
$regex_find = '([a-zA-Z]+)\\.Instance\\.'
$regex_replace = 'Resolve().'

# get all the C# files we want to search/replace through
$allFiles = Get-ChildItem -Filter *.cs -Recurse

foreach($fileToReplace in $allFiles)
    $fileString = $fileToReplace.FullName
    if([String]::Join([Environment]::NewLine, (Get-Content -Path $fileString)) -match $regex_find)
        # make the file writable so we can update it
        $fileToReplace.IsReadOnly = $false;
        Write-Host "applying fix to - $fileString"

        # here's where we load up the file iterate through each line   
        # replace any of the regex matches
        # and save the file back to the original location
        Set-Content $fileString -Value ((Get-Content -Path $fileString) | foreach { if( $_ -match $regex_find) { $_ -replace $regex_find, $regex_replace } else { $_ } } )


  • Some of the files "end of file" changed (added an extra end line in some cases)
Team Foundation Server tip to detect the changed files.

The next step requires you install the TFS Power Tools. Once installed, fire up the PowerShell console given in the start menu


I then ran the following command to have all edited files automatically detected as modified and can then be set as pending a change in TFS.

tfpt online /adds /diff /recursive .