Tuesday, November 7, 2006

Foreach loop in MSBuild

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/foreach_loop_in_msbuild.htm]

Yesterday we mentioned how MSBuild can handle conditional logic. It can also handle looping using the concept of "batching" and ItemGroups.

<Project    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">        <ItemGroup>        <ExampColl Include="Item">            <Number>123Number>        ExampColl>        <ExampColl Include="Item">            <Number>456Number>        ExampColl>        <ExampColl Include="Item">            <Number>789Number>        ExampColl>    ItemGroup>    <Target Name="ShowMessage">        <Message Text = "Number: %(ExampColl.Number)"/>    Target>Project>

The first step is to make an ItemGroup - which is simply a group of items that you can potentially loop through. Each ItemGroup needs the required "Include" attribute. For a basic example, lets just set this to "Item". The power comes in that you can add your own custom attributes to the ItemGroup, such as "Number".

You can then reference (and loop through) the ItemGroup using "%(.)", such as "%(ExampleCol1.Number)". When run, the above snippet produces the following output. Notice the Message task being called three times - once for each item in the ItemGroup.

Target ShowMessage:
    Number: 123
    Number: 456
    Number: 789


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.01

There's a lot more that you can do with Task Batching, but this is a helpful start. You can replace the Message task with any task you want, and use the '%' character in any attribute of that task. It's a lot cleaner than the DOS for loop.

No comments:

Post a Comment