MSBuild 3.5 (2008) Tidbit: You can now remove Items from ItemGroups

One of the new features of MSBuild 3.5 (2008) is the ability to remove entries from ItemGroups.  We’ve always been able to “”override” a Property value by defining that property again later in the MSBuild file.  In MSBuild 2.0 (2005), if we used that same pattern with ItemGroups, we would have duplicate entries as they are each considered distinct Items.  To remove an Item from an ItemGroup in MSBuild 2.0 you would have to create a new ItemGroup from the old one and skip the Item that you needed removed. 

In MSBuild 3.5 the removal of an Item from an ItemGroup can be achieved by using the new Remove parameter.

<ItemGroup> <Letters Include="a" /> <Letters Include="b" /> <Letters Include="1" /> <Letters Include="d" />ItemGroup><ItemGroup>
 <Letters Remove="1" />ItemGroup>

This technique is great for modifying the entries in an ItemGroup that you did not initially define because it is in an Imported MSBuild file like so:

<Project xmlns=“”>
<FilesToCopy Include=“a.aspx” />
        <FilesToCopy Include=“b.dll”
<FilesToCopy Include=“c.aspx”
<FilesToCopy Include=“d.gif”
<FilesToCopy Include=“b.pdb” />

<Project xmlns=“”>
    <Import Project=“MyCompany.Custom.targets” />
        <FilesToCopy Remove=“b.pdb” />

In the example above we had an ItemGroup named FilesToCopy that contained some files that we wanted to copy out to a staging folder for our IT group to copy to Production.  The ItemGroup is used in other builds, specifically for builds that go to Dev and QA.  It’s ok to send PDB files to the Dev and QA environments, but not to Production so we need to remove it from our ItemGroup.

Removing it is easily accomplished by adding the Remove entry in MyBuild.proj file after the Import tag so that we can manipulate the previously defined FilesToCopy ItemGroup.

The documentation for this property contains a significant number of other cool new ItemGroup manipulation features.

Documented here: