Wednesday, 4 May 2011

Updating multiple lines in Visual Studio project files

A while back I blogged about how to change text from a single line in a Visual Studio project file. What about when you need to replace a number of lines of text? This worked for me:

$regex = new-object Text.RegularExpressions.Regex "\<Target Name=`"AfterBuild`"\>.+\</Target\>", ('singleline')
Get-ChildItem -recurse -filter "*.*proj" | % { $text = (Get-Content $_.FullName) -join "`r`n"; $regex.Replace($text, "<Import Project=`"`$(SolutionDir)\Module.targets`" />`r`n") | Set-Content "$($_.FullName).tmp" }

We have to do a little more work compared to the first approach. We need to join all the individual lines into one single line so that the regex will operate correctly. Because we want to set options on the regex, we create that separately too. Note that the above example writes to a new .tmp file, so you can confirm the replace is working properly before overwriting the original files.

Project files are just XML files, so this technique should work for any XML file.

In my case, the solution was checked in to TFS, so the project files will need to be checked out before they can be updated. The checkout can be incorporated into the pipeline like this:

Get-ChildItem -recurse -filter "*.Service.*proj" | % { & "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkout $_.FullName; $text = (Get-Content $_.FullName) -join "`r`n"; $regex.Replace($text, "<Import Project=`"`$(SolutionDir)\Web.Module.targets`" />`r`n") | Set-Content "$($_.FullName).tmp" }

References:

No comments: