How can I add an AfterBuild event to a project when installing my NuGet package? How can I add an AfterBuild event to a project when installing my NuGet package? powershell powershell

How can I add an AfterBuild event to a project when installing my NuGet package?


As of NuGet 2.5, by convention, if you add a targets file at build\{packageid}.targets (note 'build' is at the same level as content and tools), NuGet will automatically add an Import to the .targets file in the project. Then you don't need handle anything in install.ps1. The Import will be automatically removed on uninstall.

Also, I think the recommended way to do what you want would to create a separate target that is configured to run after the standard "Build" target:

<?xml version="1.0" encoding="utf-8" ?><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">    <Target Name="NuGetCustomTarget" AfterTargets="Build">        <PropertyGroup>            <PathToOutputExe>..\bin\Executable.exe</PathToOutputExe>            <PathToOutputJs>"$(MSBuildProjectDirectory)\Scripts\Output.js"</PathToOutputJs>            <DirectoryOfAssemblies>"$(MSBuildProjectDirectory)\bin\"</DirectoryOfAssemblies>        </PropertyGroup>        <AspNetCompiler Condition="'$(MvcBuildViews)'=='true'" VirtualPath="temp" PhysicalPath="$(ProjectDir)" />        <Exec Command="$(PathToOutputExe) $(PathToOutputJs) $(DirectoryOfAssemblies)" />    </Target></Project>


Here's a script that adds a afterbuild target. It also user the NugetPowerTools mentioned above.

$project = Get-Project$buildProject = Get-MSBuildProject$target = $buildProject.Xml.AddTarget("MyCustomTarget")$target.AfterTargets = "AfterBuild"$task = $target.AddTask("Exec")$task.SetParameter("Command", "`"PathToYourEXe`" $(TargetFileName)")

The hard part was getting the quotes right. This is what it looks like in my powertools script.


You can use the MSBuild Api directly, as in this blog post.

Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'$msbProject = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1# use $msbProject to add/change AfterBuild target

Or you could use NugetPowerTools which adds Powershell command Get-MSBuildProject to do much the same thing.

Also, see this forum post for more details on adding the new target.