0

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.

AxD
  • 2,714
  • 3
  • 31
  • 53

1 Answers1

1

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.

Jonathan Dodds
  • 2,654
  • 1
  • 10
  • 14
  • Thank you for this excellent answer! I added this condition because I wanted to make sure after reading the warning of the [Delete](https://learn.microsoft.com/en-us/visualstudio/msbuild/delete-task?view=vs-2019) task: "You can easily delete the wrong files with expressions like `$(SomeProperty)\**\*.*` or `$(SomeProperty)/**/*.*`, especially if the property evaluates to an empty string". – AxD Jan 11 '23 at 00:27