You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现通过dotnet CLI安装NuGet包时自动运行命令

解决方案

为什么Init.ps1失效

传统tools目录下的Init.ps1/Install.ps1类PowerShell脚本仅能在Visual Studio的NuGet包管理器UI安装时触发,dotnet CLI、PackageReference引用模式下微软官方直接禁用了这类脚本的自动执行,这是设计层面的限制,所以原有方案无法生效。

推荐实现方案:基于MSBuild Target触发执行

这是目前跨dotnet CLI、IDE全环境兼容的官方推荐实现方式,利用NuGet自动导入包内build目录下同名.targets文件的机制,在指定构建节点触发exe执行。

实现步骤

  1. 资源准备
    将待执行的exe及其依赖文件全部放到NuGet包的tools目录下。
  2. 编写MSBuild targets文件
    在你的包项目中新建与包ID同名的.targets文件,例如你的包ID是My.Custom.Package,文件名为My.Custom.Package.targets,内容示例如下:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- AfterTargets可根据你需要的执行时机调整:Restore=还原后执行,BeforeBuild=构建前执行 -->
  <Target Name="RunCustomExeAfterInstall" AfterTargets="Restore" Condition="!Exists('$(IntermediateOutputPath)custom_exe_executed.flag')">
    <PropertyGroup>
      <!-- 用MSBuildThisFileDirectory自动定位路径,无需硬编码包版本 -->
      <CustomExePath>$(MSBuildThisFileDirectory)../tools/YourExeName.exe</CustomExePath>
    </PropertyGroup>
    <!-- 执行exe,可根据需要调整ContinueOnError参数 -->
    <Exec Command="&quot;$(CustomExePath)&quot;" ContinueOnError="false" />
    <!-- 生成标记文件,避免每次restore都重复执行,删掉这段则每次restore都会执行 -->
    <Touch Files="$(IntermediateOutputPath)custom_exe_executed.flag" AlwaysCreate="true" />
  </Target>
</Project>
  1. 配置打包规则
    在你的.nuspec文件中添加文件打包配置,确保targets文件放到build目录,exe放到tools目录:
<files>
  <file src="My.Custom.Package.targets" target="build/My.Custom.Package.targets" />
  <file src="path/to/your/YourExeName.exe" target="tools/YourExeName.exe" />
  <file src="path/to/your/*.dll" target="tools/" />
</files>

注意事项

  • 如果你的exe是.NET跨平台程序,可以把执行命令改成dotnet &quot;$(CustomExePath)&quot;,适配Linux、macOS环境
  • 如果不需要限制仅执行一次,删掉Target里的Condition判断和Touch节点即可
  • 可根据业务需要调整AfterTargets参数,选择合适的执行时机

内容的提问来源于stack exchange,提问作者jiten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 22:48:01