如何在安装NuGet包时将AfterBuild事件添加到项目中?

时间:2011-11-11 15:05:05

标签: powershell nuget-package

我有一个nuget包,它添加了一个可执行文件,我需要在项目每次构建后运行。

我可以通过在每个项目文件中添加一个部分来手动添加:

<Target Name="AfterBuild">
    <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>

我在安装nuget软件包时如何将其添加到项目中? (即使用Install.ps1文件中的DTE $项目对象)

我非常感谢你提供任何帮助。

由于

理查德

3 个答案:

答案 0 :(得分:5)

NuGet 2.5开始,按照惯例,如果您在build\{packageid}.targets添加目标文件(注意'build'与内容和工具处于同一级别),NuGet会自动将导入添加到项目中的.targets文件。然后你不需要在install.ps1中处理任何东西。导入将在卸载时自动删除。

另外,我认为推荐的方法可以创建一个单独的目标,配置为在标准的“Build”目标之后运行:

<?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>

答案 1 :(得分:3)

这是一个添加后构建目标的脚本。它还使用上面提到的NugetPowerTools。

$project = Get-Project
$buildProject = Get-MSBuildProject

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

困难的部分是正确的报价。这就是我的powertools脚本中的样子。

答案 2 :(得分:1)

您可以直接使用MSBuild Api,如此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

或者你可以使用NugetPowerTools添加Powershell命令Get-MSBuildProject来做同样的事情。

另外,有关添加新目标的详细信息,请参阅此forum post

相关问题