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

如何将Jenkins Pipeline的sh步骤在Windows默认改为PowerShell?

如何让Jenkins Pipeline的sh步骤在Windows代理默认使用PowerShell?

我之前也跟你有一样的需求——想跨平台用统一的sh步骤写命令,不用在Windows节点上特意切换bat或powershell步骤。把Windows代理的sh默认改成PowerShell确实是最优解,毕竟PowerShell自带一堆bash别名,大部分常用命令都能直接复用,完美对齐Linux上的bash体验。下面给你两种可行的配置方式,按需选择:

一、全局配置(所有Windows代理生效)

如果你想让所有Windows代理的sh步骤都默认用PowerShell,可以在节点层面配置:

  • 登录Jenkins后台,依次进入 Manage Jenkins → Manage Nodes and Clouds
  • 找到目标Windows代理节点,点击节点名称进入配置页
  • 滚动到Node Properties区域,勾选Tool Locations
  • 点击Add,在Tool下拉菜单里选Shell,然后在Home输入框填PowerShell的路径:
    • 系统自带的Windows PowerShell路径:C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    • 如果你装了PowerShell Core(新版),路径一般是:C:\Program Files\PowerShell\7\pwsh.exe
  • 保存配置就搞定了,之后这个节点上所有流水线的sh步骤都会默认调用PowerShell

二、局部配置(仅特定流水线生效)

如果只需要某条流水线在Windows代理上用PowerShell执行sh步骤,直接在Jenkinsfile里配置即可:

方式1:用defaultShell全局设置流水线的默认Shell

pipeline {
    agent { label 'windows-agent' } // 你的Windows代理标签
    options {
        // 给这条流水线指定默认Shell为PowerShell
        defaultShell 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
    }
    stages {
        stage('Test Cross-Platform Commands') {
            steps {
                sh '''
                    # 直接用bash风格命令就行,PowerShell会自动识别别名
                    ls
                    echo "Hello from PowerShell via sh step!"
                    mkdir test-dir
                '''
            }
        }
    }
}

方式2:单个sh步骤指定executable

如果只是个别sh步骤需要用PowerShell,也可以单独指定:

sh(
    script: 'ls -la',
    executable: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
)

小提示:验证是否生效

你可以在sh步骤里加一行命令确认当前用的是PowerShell:

sh '$PSVersionTable'

执行后会输出PowerShell的版本信息,就能确认配置成功了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:27:32