MSBuild trick for making <Exec> calls more maintainable

One of my pet peeves with MSBuild’s <Exec> task is how long the lines get when you have lots of arguments.

I ran across a trick yesterday in a blog comment made by someone named Romain and thought it was a very nice solution to this problem. When you expand items using this form @(items, ‘DELIMITER’), it allows you to specify a delimiter to use between the items. In the case of a command line, you use a space. Thanks Romain.

<ItemGroup>
  <XmlPreprocessArgs Include="/nologo"/>
  <XmlPreprocessArgs Include="/v"/>
  <XmlPreprocessArgs Include="/x:&quot;$(InstallDir)\Environments\$(ApplicationName).EnvironmentSettings.xml&quot;"/>
  <XmlPreprocessArgs Include="/i:&quot;$(InstallDir)\UI.Shell.exe.config%3B$(InstallDir)\ClientLogging.config&quot;"/>
  <XmlPreprocessArgs Include="/e:&quot;$(Environment)&quot;"/>
</ItemGroup>

<Exec Command="&quot;$(InstallDir)\Environments\XmlPreprocess.exe&quot; @(XmlPreprocessArgs,' ')"
      WorkingDirectory="$(InstallDir)\Environments" />

3 Comments

  • I would personally prefer using a property instead of an item. For example:


    /nologo
    $(XmlPreprocessArgs) /v
    $(XmlPreprocessArgs) /x:&quot;$(InstallDir)\Environments\$(ApplicationName).EnvironmentSettings.xml&quot;
    $(XmlPreprocessArgs) /i:&quot;$(InstallDir)\UI.Shell.exe.config%3B$(InstallDir)\ClientLogging.config&quot;
    $(XmlPreprocessArgs) /e:&quot;$(Environment)&quot;







    Sayed Ibrahim Hashimi

  • Yes, I agree, a property is a good solution, and it's only slightly more verbose. The nice thing about MSBuild is that it's flexible enough to have choices. Although in my opinion the NAnt syntax for exec still beats both solutions. NAnt has a nested element.




    etc...


    I just had to post this because when I saw it, it made me smile to see the items with delimiter expansion used that way. I had never made that connection and thought it was very clever.

  • You can make it more readable by avoiding use of &quot; in your commands. Enclose the attributes in single quotes instead of double quotes and then you can use double quotes safely inside them:


    becomes

Comments have been disabled for this content.