Friday, September 9, 2016

Powershell, XML and Visual Studio build event

Visual Studio provides a lot of capability, but sometimes you need a little Powershell. I needed to update an XML file in my solution based on the projects build configuration. If the configuration was "Release" setup a node in the XML to be value A. If the configuration was "Debug" setup a node in the XML to be value B. I actually did not realize how easy it is to work with XML within Powershell. I found a nice little start on StackOverflow.

My XML was more complex of course but it is still pretty easy to work with. Here is my post-build event.

"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" -file ..\..\..\..\Scripts\ToggleXMLValues.ps1 $(ConfigurationName) $(TargetDir)

Then in a Powershell file I wrote some pretty simple code.

param ([string]$configName, [string]$outputDir)

$doc = [xml](Get-Content "$($outputDir)\config\myfile.xml")

if ($configName -eq "Release")
{
 $doc.Configuration.Global.Storages.Storage[0].Url = "URL 1"
}
else
{
 $doc.Configuration.Global.Storages.Storage[0].Url = "Url 2"
}

$doc.save("$($outputDir)\config\myfile.xml")

In my case I had an XML document that looked like this.

<Configuration>
  <Global>
    <Storages>
      <Storage Url="My URL"/>
      <Storage/>
    <Storages>
  </Global>
</Configuration>

With that little bit of code I can now toggle this value whenever I build.