22

Is there a way to remove the contents of an ItemGroup without resorting to Targets? I'm looking for something equivalent to:

<ItemGroup>
  <MyItemGroup Remove="@(MyItemGroup)"/>
</ItemGroup>

Thanks

Zain Rizvi
  • 23,586
  • 22
  • 91
  • 133

2 Answers2

18

No, as the documentation states, Remove can only be included in a ItemGroup inside a Target. I'm not sure why using a Target is an issue in your case, but if want to use the 'Remove' step for every build config, then add it to one of the BeforeXXXX AfterXXX hooks, like BeforeBuild.

ItemGroup 'Remove' Documentation

Starting in the .NET Framework 3.5, Target elements may contain ItemGroup elements that may contain item elements. These item elements can contain the Remove attribute, which removes specific items (files) from the item type. For example, the following XML removes every .config file from the Compile item type.

<Target>
  <ItemGroup>
    <Compile Remove="*.config"/>
  </ItemGroup>
</Target>
Ritch Melton
  • 11,498
  • 4
  • 41
  • 54
  • You're right. It is not possible to do it outside of a target. I deleted my answer and I selected your answer as useful ;) – Ludwo Oct 27 '11 at 13:24
  • @Ludwo - Good to know. I thought I had missed something. – Ritch Melton Oct 27 '11 at 13:25
  • 4
    Caveat - the *.config will only match files that actually exist. Suppose @(Compile) is A.config;B.config but only A.config exists. Then after the Remove, @(Compile) will still contain B.config. And if the items do not represent files, there is no wildcard AFAIK. – Paul Williams Oct 16 '14 at 15:08
  • 3
    What would you have in a msbuild script that you want to remove that is a) a file that doesn't exist b) is not a file? – Ritch Melton Oct 16 '14 at 15:29
  • @RitchMelton - Items not representing files are sometimes used in MSBuild scripts; see for example the `Result` output parameter of the `XmlPeek` task (https://msdn.microsoft.com/en-us/library/ff598684.aspx). Additionally, even with items that do represent files, it is sometimes appropriate to use `Remove` without querying the file system; see for example these lines in `Microsoft.Common.CurrentVersion.targets`: https://github.com/Microsoft/msbuild/blob/f98d5d96efe032b8990e3c3b404ab2dbd5d6b043/src/Tasks/Microsoft.Common.CurrentVersion.targets#L2978-L2982 – weir Jun 16 '17 at 17:40
17

Now there is.

What's New in MSBuild 15

  • Item Element outside targets has a new Update attribute. Also, the restriction on the Remove attribute has been eliminated.
weir
  • 4,521
  • 2
  • 29
  • 42