Monday, November 6, 2006

Conditional Logic (If-Then-Else) in MSBuild

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/conditional_logic_ifthenelse_in_msbuild.htm]

MSBuild provides the ability to do an if-then-else control structure, using the Condition attribute, which is available to every task. Simply put, the task only runs if the given condition is true.

An If-Then-Else means "if the condition is true, run the first statement, else run the second statement". This is logically equivalent to: If 'X' is true, run S1; If 'X' is false, then run S2. We can use the task's Condition attribute, with the ! ('Not') Operator to achieve this. For example, in the snippet below, if the variable "RunTask" is true, then the first line is run, else the second line is run.

    <Message Condition="$(RunTask)" Text="Do X" />
    <Message Condition="!$(RunTask)" Text="Do not do X" />

You can see a list of allowed conditional expressions in the MSBuild reference. It includes operators ( <, >, <=, >=, ==, !=, !, And, Or), parenthesis, and even an "Exists" function to see if a file exists.

No comments:

Post a Comment