Noel Kennedy
Noel Kennedy

Reputation: 12268

How do I change a property's value based on a conditional in msbuild?

I would like to change the value of a property if it is a certain value. In C# I would write:

if(x=="NotAllowed")
  x="CorrectedValue;

This is what I have so far, please don't laugh:

 <PropertyGroup>
    <BranchName>BranchNameNotSet</BranchName>
  </PropertyGroup>

///Other targets set BranchName

 <Target Name="CheckPropertiesHaveBeenSet">
    <Error Condition="$(BranchName)==BranchNameNotSet" Text="Something has gone wrong.. branch name not entered"/>
      <When Condition="$(BranchName)==master">
        <PropertyGroup>
          <BranchName>MasterBranch</BranchName>
        </PropertyGroup>
      </When>
  </Target>

Upvotes: 20

Views: 16823

Answers (2)

Julien Hoarau
Julien Hoarau

Reputation: 50000

You can do that using Condition on Property:

<PropertyGroup>
  <BranchName>BranchNameNotSet</BranchName>
</PropertyGroup>

<Target Name="CheckPropertiesHaveBeenSet">
  <!-- If BranchName equals 'BranchNameNotSet' stop the build with error-->
  <Error Condition="'$(BranchName)'=='BranchNameNotSet'" Text="Something has gone wrong.. branch name not entered"/>

  <PropertyGroup>
    <!-- Change BranchName value if BranchName equals 'master' -->
    <BranchName Condition="'$(BranchName)'=='master'">MasterBranch</BranchName>
  </PropertyGroup>

</Target>

Info on When and Choose:

The Choose, When, and Otherwise elements are used together to provide a way to select one section of code to execute out of a number of possible alternatives.

Choose elements can be used as child elements of Project, When and Otherwise elements.

In your code sample, you use When without Choose and within a target, that is not possible.

Upvotes: 26

stijn
stijn

Reputation: 35921

this sets BranchName to the string 'CorrectedValue' if it's value equals 'NotAllowed':

<PropertyGroup>
   <BranchName Condition="'$(BranchName)'=='NotAllowed'">CorrectedValue</BranchName>
</PropertyGroup>

Upvotes: 3

Related Questions