How to use user-defined variable inside post-build event?

stukselbax picture stukselbax · Jan 19, 2014 · Viewed 13.6k times · Source

I want to use local variable inside the PostBuild event, but I could not understand how to use it inside. Here my Post-Build event commands (param is the named parameter that can be passed through the msbuild /p switch):

set fold=$(TargetDir)
if defined param (set fold=$(TargetDir)$(param)\)
if not exist "%fold%" md "%fold%"
copy /y "$(TargetPath)" "%fold%"

When building the solution I get:

msbuild PrePostBuildEvents.sln /p:param=ext

...

PostBuildEvent:
  set fold=G:\prj\work\PrePostBuildEvents\bin\Debug\
  if defined param (set fold=G:\prj\work\PrePostBuildEvents\bin\Debug\ext\)
  if not exist "%fold%" md "%fold%"
  copy /y "G:\prj\work\PrePostBuildEvents\bin\Debug\PrePostBuildEvents.dll" "%fold%"
  The file cannot be copied onto itself.
          0 file(s) copied.

If I change %fold% to $(fold), I get another result, but it is also wrong:

PostBuildEvent:
  set fold=G:\prj\work\PrePostBuildEvents\bin\Debug\
  if defined param (set fold=G:\prj\work\PrePostBuildEvents\bin\Debug\ext\)
  if not exist "" md ""
  copy /y "G:\prj\work\PrePostBuildEvents\bin\Debug\PrePostBuildEvents.dll" ""
  The filename, directory name, or volume label syntax is incorrect.
          0 file(s) copied.

What I'm doing wrong?

Answer

Squirrel picture Squirrel · Feb 20, 2014

Firstly, use the AfterBuild msbuild target rather than PostBuild event. This will give msbuild more information about what you're trying to do and done correctly should mean a faster incremental compile.

Environment variables can be used in AfterBuild events: http://msdn.microsoft.com/en-us/library/ms171459.aspx

Ideally once you've run msbuild once, when you run it a second time it should do no work skipping compiles and not bothering to copy things around as the files are already there.