Search code examples
msbuildmsbuild-taskmsbuild-targetmsbuild-15

<When> element below <Choose> element is unknown — why?


I manually edited my MSBuild file to execute a few commands only when a certain condition is met:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  ...
  <Target Name="Rebuild" DependsOnTargets="Clean">
    <Choose>
      <When Condition="'$(MSBuildProjectDirectory)'!=''" >
        <RemoveDir Directories="$(MSBuildProjectDirectory)\intermediate" />
        <RemoveDir Directories="$(MSBuildProjectDirectory)\$(BaseIntermediateOutputPath)" />
        <RemoveDir Directories="$(MSBuildProjectDirectory)\$(BaseOutputPath)" />
        <Message Text="Artifact files have been deleted." />
      </When>
    </Choose>
  </Target>
</Project>

Yet, Visual Studio 2019 denies to load the .vcxproj file. There error message is:

<When> element below <Choose> elements is unknown.

What did I do wrong here?

According to https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-conditional-constructs?view=vs-2019 I was convinced that everything I did was by the book.


Solution

  • See Choose element (MSBuild) and note the parent elements. Choose cannot be used within a Target.

    However, $(MSBuildProjectDirectory) will always be set with a value and <When Condition="'$(MSBuildProjectDirectory)' != ''" > will always be true.