Conditional Build Events in Visual Studio 2005

A customer asked me if it was possible to create a post-build event in Visual Studio 2005 that would only be run if the active mode was “Debug.”

A brief search in the Internet (using, to keep getting “a piece of the Π”) revealed that there was no “built-in” support or any solution previously posted. However, the solution is rather simple, almost trivial. Build events are just commands that get passed to the command line interpreter (with some escaping taking place).

I remember that MS-DOS used to support IF statements for batch files. The Windows Server 2003 command interpreter (cmd.exe) still does, and this is the syntax:

IF [NOT] condition command

Type “help if” at the command prompt to see more information. IIRC, the MS-DOS IF statement was not nearly as extensive as the one supported by cmd.exe.

Combine this with the fact that the build events provide several “macros” (variables is what I would call them) that are replaced with values before the command is sent to the command line, and you get this command:

IF /I "$(ConfigurationName)" == "Debug" <command to run>

The /I switch makes the comparison case-insensitive. The quotes around the macro name are necessary in order to make the command interpreter see it as a string. <command to run> can be replaced with the command. If the command contains spaces, it must also be enclosed between quotes.

If you need to execute multiple commands for a single condition, there are two ways to achieve this: either repeat the IF statement on as many separate lines as you have conditional build events, or put them all in a batch file. The latter method would definitely be the preferred method. Note that you cannot put parentheses () around the multiple commands. In a batch file, each command must be and can be separated by a newline character. However, each build event must be separated from the next one by a newline character as well. There is an inherent conflict there.

Let me know what you think, or ask a question...

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.