Conditional Visual Studio build event scripts

In some projects there’s a need for manual operations after compilation. It might be to copy files, sign code or whatever. Of course it would be great to make these operations automatic, and that’s what build event scripts in Visual Studio are for.

Basically a build event script is a BAT file with some variables that are replace by Visual Studio when executing it. You create a build event script in the Properties dialog box of the project and here’s an example of what it may look like (in this case we package a set of files from the project into a Zip archive used for deploying the application):

REM If Debug config, do nothing...
if $(ConfigurationName) == Debug then goto endif

mkdir $(TargetDir)Imports\
mkdir $(TargetDir)Reports\
mkdir $(TargetDir)Faktureringsunderlag\

del /F /Q $(TargetDir)Imports\*.*
del /F /Q $(TargetDir)Reports\*.*
del /F /Q $(TargetDir)Faktureringsunderlag\*.*

copy /Y $(ProjectDir)Imports\*.xlt $(TargetDir)Imports\
copy /Y $(ProjectDir)Reports\*.rpt $(TargetDir)Reports\
copy /Y $(ProjectDir)Faktureringsunderlag\*.xlt $(TargetDir)Faktureringsunderlag\

REM Create Zip archive
del /Q

$(SolutionDir)Utils\7z.exe a Faktureringsunderlag Imports Reports
ErrorHandler.dll janus*.dll Microsoft.ApplicationBlocks.Data.dll new_*.dll
new_SFIStarter.exe SFI*.dll Svea.exe Svea.exe.config


The example illustrates several points:

  • The operations are conditional, i.e. are not done in Debug compilation. There’s no point it taking that time if we’re about to deploy the application.
  • It makes sense to use options for the respective tool to disable prompting (e.g. “Are you sure you want to delete XXX”) since we’ll never be able to answer.
  • Any command line utility can be used. In this case I have downloaded the great 7-Zip util and copied it’s binaries into the solution so that it’s always available on every developer’s computer.

Kind of useful, ain’t it? Of course, there are other ways of doing this, e.g. using MSBuild, but I find this method easy to understand and manage.

2 thoughts on “Conditional Visual Studio build event scripts”

  1. I see “TagetDir”. Don’t you mean “TargetDir”?
    This tells me you never even ran this. Or modified it after testing it, which makes testing pointless.

  2. Of course this has been tested. Do you really think anyone comes up with an example like that without testing it? You have to work on your attitude…

    The script happens to work because it turns out that the current directory is the target directory, so the faulty variable is not really needed. When running the script it’s evaluated to an empty string so the script works regardless.

    I corrected the misspelled word just to be correct.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

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