Monday, April 4, 2011

MSBuild - sort an ItemGroup

An automated MSBuild script that creates a database from scratch started failing after switching from vcvarall.bat provided by a Visual Studio 2008 install to the Visual Studio 2010 version.

For some unknown reason, the order of files listed in a ItemGroup was reversed. With files beginning with an underscore running last rather than first.

The issue was resolved by explicitly sorting the ItemGroup using a custom task from the MSBuild Extension Pack.


    <!-- Have a fallback check depending on path locally or on build server -->
    <PropertyGroup>
        <TPath>$(MSBuildProjectDirectory)\ExtensionPack\MSBuild.ExtensionPack.tasks</TPath>
        <TPath Condition="Exists('C:\Program Files (x86)\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks')">C:\Program Files (x86)\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks</TPath>
    </PropertyGroup>
    <Import Project="$(TPath)"/>

    <!-- ... -->

    <Target Name="MainData">
        <Message Text="Inserting Data Main (Main Data)" />

        <!-- Sort an ItemGroup alphabetically -->
        <MSBuild.ExtensionPack.Framework.MsBuildHelper TaskAction="Sort" InputItems1="@(MainDataFiles)">
            <Output TaskParameter="OutputItems" ItemName="sorted"/>
        </MSBuild.ExtensionPack.Framework.MsBuildHelper>
        <Message Text="Sorted Items: %(sorted.Identity)"/>
    
        <Exec Command="$(SqlCmdPrefix) -i %(sorted.Identity)" />
    </Target>


See Also: