如何实现通过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执行。
实现步骤
- 资源准备
将待执行的exe及其依赖文件全部放到NuGet包的tools目录下。 - 编写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=""$(CustomExePath)"" ContinueOnError="false" /> <!-- 生成标记文件,避免每次restore都重复执行,删掉这段则每次restore都会执行 --> <Touch Files="$(IntermediateOutputPath)custom_exe_executed.flag" AlwaysCreate="true" /> </Target> </Project>
- 配置打包规则
在你的.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 "$(CustomExePath)",适配Linux、macOS环境 - 如果不需要限制仅执行一次,删掉Target里的Condition判断和Touch节点即可
- 可根据业务需要调整
AfterTargets参数,选择合适的执行时机
内容的提问来源于stack exchange,提问作者jiten
相关产品推荐
相关产品推荐

