ygoe
ygoe

Reputation: 20374

Run an MSBuild target after a failed build

My custom MSBuild tasks performs some steps before and after the actual build. It is essential that the steps after the build are always executed to clean up some files. I currently have two targets defined:

<Target Name="NrtPatchAssemblyInfo" BeforeTargets="BeforeBuild">

and

<Target Name="NrtRestoreAssemblyInfo" AfterTargets="AfterBuild">

The first one is always executed, but the second only runs after a successful build. If the build failed by the compiler, for example due to a syntax error in a code file, the second target isn't run.

What can I do to change this and always have the second task executed?

I couldn't find a list of target names MSBuild usually uses. These names are just copied from other sources.

Upvotes: 5

Views: 2545

Answers (1)

stijn
stijn

Reputation: 35901

MsBuild stops running any further targets when an error occurs (unless ContinueOnError is modified somewhere but you can't go edit all installed msbuild files to get that working). One solution is to use the OnError element. This has to be set on the target which fails (or a parent of that target, I assume) so you'll have to select one which is used in the actual build and override it. For a C++ build you'd override the Build target, copy the definition from Microsoft.Common.CurrentVersion.targets and add OnError. Example code (must be inserted in the project file after the Microsoft.Cpp.targets Import!):

<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Target Name="RunOnError">
  <Message Text="OOPS!" />
</Target>
<Target
    Name="Build"
    Condition="'$(_InvalidConfigurationWarning)' != 'true'"
    DependsOnTargets="$(BuildDependsOn)"
    Returns="$(TargetPath)">
  <OnError ExecuteTargets="RunTargetAfterBuild" />
</Target>

To figure out which targets get executed just run the build with Detailed verbosity.

Upvotes: 4

Related Questions