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

如何在Jenkins的PowerShell脚本中调用${tool 'MSBUILD'}的配置路径?

实现方案

核心逻辑

Jenkins的${tool '工具名'}是Jenkins流水线上下文特有的语法,只能在Jenkinsfile层面解析,无法直接在内嵌的PowerShell代码中生效,需要先在流水线中拿到MSBuild的实际路径,再传入PowerShell脚本使用。

方案1:PowerShell代码直接内嵌在Jenkinsfile中

  1. 先在Jenkins流水线脚本中调用tool方法拿到MSBuild的安装路径,拼接为msbuild.exe的完整路径
  2. 用"""包裹PowerShell代码块,将Jenkins侧拿到的路径变量插值传入,注意转义PowerShell自有变量前的$符号
  3. PowerShell中执行带空格路径的可执行文件需要加调用运算符&

代码示例:

script {
    // Jenkins流水线侧先获取MSBuild完整路径
    def msbuildExe = "${tool 'MSBuild 16'}\\msbuild.exe"
    powershell """
        task Compile -depends Clean, DotNetCliVersion, Restore, AssemblyInfo {
            exec { & "$msbuildExe" /t:clean /v:q /nologo /p:Configuration=`$configuration `$product.sln }
            exec { & "$msbuildExe" /t:build /v:q /nologo /p:Configuration=`$configuration `$product.sln }
        }
    """
}

注意:代码中$configuration、$product前的反引号是PowerShell的转义符,用于避免$被Jenkins提前解析。

方案2:PowerShell代码为独立的ps1脚本文件

  1. 在Jenkinsfile中拿到MSBuild路径后,作为启动参数传递给ps1脚本
  2. 在ps1脚本中新增参数接收传入的MSBuild路径,直接调用即可

Jenkinsfile示例:

script {
    def msbuildExe = "${tool 'MSBuild 16'}\\msbuild.exe"
    // 调用独立ps1脚本并传入MSBuild路径参数
    powershell "./你的构建脚本名.ps1 -MsbuildPath `"$msbuildExe`""
}

PowerShell脚本示例:

# 脚本开头新增参数接收
param(
    [string]$MsbuildPath
)

task Compile -depends Clean, DotNetCliVersion, Restore, AssemblyInfo {
    exec { & $MsbuildPath /t:clean /v:q /nologo /p:Configuration=$configuration $product.sln }
    exec { & $MsbuildPath /t:build /v:q /nologo /p:Configuration=$configuration $product.sln }
}

注意事项

  • 确保tool方法中传入的MSBuild名称和Jenkins全局工具配置中设置的名称完全一致
  • 如果是Linux/macOS节点,路径拼接需要将\\改为/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:36:04