Share via


How to call the same target multiple times at different build stages?

The code sample describes how you can invoke a particular target (i.e. init) multiple times at different build stages (i.e BeforeBuild, AfterBuild, etc). Please note that you can easily invoke this common target with different custom properties based on build state (i.e we are passing different value to stage property based on invoking target.)

 

<Project xmlns="https://schemas.microsoft.com/developer/msbuild/2003">

<!-- main target that will be invoked -->
<Target Name = "Build" DependsOnTargets="BeforeBuild;CoreBuild;AfterBuild"/>

 

<Target Name="BeforeBuild">

  <MSBuild Targets="InitTask"
Properties ="Stage=BeforeBuild"
Projects="$(MSBuildProjectFile)"/>

  <Message Text="Executing before build ... "/>        

</Target>

 

<Target Name="AfterBuild">

  <MSBuild Targets="InitTasK"
Properties ="Stage=AfterBuild"
Projects="$(MSBuildProjectFile)"/>

  <Message Text="Executing after build ... "/>           

</Target>        

 

<!-- Generic target that will invoke the common task for each stage with proper properties -->
<Target Name="InitTask">

  <MSBuild Condition=" '$(Stage)'=='BeforeBuild' "
Targets="Init"
Properties ="Stage=BeforeBuild"
Projects="$(MSBuildProjectFile)"/>

  <MSBuild Condition=" '$(Stage)'=='AfterBuild' "
Targets="Init"
Properties ="Stage=AfterBuild"
Projects="$(MSBuildProjectFile)"/>

</Target>  

 

<!-- The actual task to be executed at a particular stage -->
<Target Name="Init">
<Message Text="Init $(Stage)"/>
</Target>

<Target Name="CoreBuild"/>        

</Project>

Comments

  • Anonymous
    December 08, 2008
    That is the perfect (and simple) solution to my problem! I was also trying to call the same target over and over too using a different set of properties each time. But because of the number of properties that changed, it was becoming very difficult and hard to predict the results when using normal msbuild batching.