How can I invoke my MSBuild Target when msbuild.exe starts and when it ends

To execute a solution-wide Before and After targets, you would create two MSBuild project files named “after.<SolutionName>.sln.targets” and “before.<SolutionName>.sln.targets” in the same folder as your solution.

To do this on all solutions, you would drop your custom solution-level after targets files into the path $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore\ or $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter. When those solutions are built, it will import all project files in these folders if they exist.

To verify the above, open a command prompt and navigate to the folder containing your solution file. Type “SET MSBuildEmitSolution=1”. Then run msbuild.exe <SolutionName>. You will see that msbuild has saved the metadata project files <SolutionName>.sln.metaproj and <SolutionName>.sln.metaproj.tmp in the same path as your solution.

View the <Import /> declarations at the top and bottom of the file and you’ll notice the conditional imports that allow you to declare solution-specific before and after targets, or global solution-specific before and after targets.

Edit:

It appears that this would only be applicable to command line or team builds, but not from within Visual Studio.

I added this to my After.Solution.sln.targets file:

<Target Name="Banana" AfterTargets="Build">
    <Message Text="*** BEGIN BANANA ***" Importance="high" />
    <Message Text=" _                                          " Importance="high" />
    <Message Text="//\                                         " Importance="high" />
    <Message Text="V  \                                        " Importance="high" />
    <Message Text=" \  \_                                      " Importance="high" />
    <Message Text="  \,'.`-.                                   " Importance="high" />
    <Message Text="   |\ `. `.                                 " Importance="high" />
    <Message Text="   ( \  `. `-.                        _,.-:\" Importance="high" />
    <Message Text="    \ \   `.  `-._             __..--' ,-';/" Importance="high" />
    <Message Text="     \ `.   `-.   `-..___..---'   _.--' ,"https://stackoverflow.com/" Importance="high" />
    <Message Text="      `. `.    `-._        __..--'    ,"https://stackoverflow.com/" Importance="high" />
    <Message Text="        `. `-_     ``--..''       _.-' ,'   " Importance="high" />
    <Message Text="          `-_ `-.___        __,--'   ,'     " Importance="high" />
    <Message Text="             `-.__  `----'''    __.-'       " Importance="high" />
    <Message Text="                  `--..____..--'            " Importance="high" />
    <Message Text="*** END BANANA ***"  Importance="high" />
</Target>

From the command line: Bananas!

On a TFS build: Bananas!

Visual Studio: No bananas 🙁

Leave a Comment