Build events in Visual Studio are ones that get triggered before a build starts or after a build finishes.
By specifying a custom build event, you can automatically run commands before a build starts or after it finishes. For example, you can run a .bat file before a build starts or copy new files to a folder after the build is complete. Build events run only if the build successfully reaches those points in the build process.
Which basically means, if pre-build event commands fail, the code won't get compiled any more, and the build fails; if post-build event commands fail, the build is considered to be failed as well.
Tips for Authoring Build Event Commands
Commands in pre/post build events are running in the directory specified by the macro
$(OutDir). For example, in
bin\Releaseor any other value set under Output path. To change the working directory in build event commands, use
Prefix batch file commands with
cmd /cto ensure commands after it will get executed, e.g.
Enclose file paths with quotes to avoid syntax error, e.g.
Click Edit Pre/Post-build… -> Macros>> for a list of available macros and their value, or check the VS Doc.
Ignore errors in build event commands
If pre/post build events exit with code other than 0, the build fails.
To suppress errors in build events, add
exit 0 or
set ERRORLEVEL=0 to the end of the commands.
However, this is not enough in some cases as Visual Studio or more exactly MSBuild.exe recognizes error and warning messages output by pre/post build events. If an error message is recognized, the exit code of build event commands will be set to -1 if it would be 0 otherwise, and the build will be considered a failure.
Thus, in order to avoid build failure caused by error messages output by build event commands, we need to redirect their output to another file or discard it totally. For example,
SomeCommand >nul 2>nul SomeOtherCommand >out.txt 2>err.txt
Messages that will be matched as error/warning will pass the following regex (case insensitive):
For details on this part, please check the references.