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

在GitHub Actions中用PowerShell执行远程Linux Bash脚本失败求助

问题分析与解决方案

你的错误直接原因是PowerShell Here-String的终止符@"前面不能有任何空白字符,代码里的终止符前有空格导致解析失败。但更核心的问题是对bash -s的用法理解有误——bash -s是从标准输入读取脚本内容,而非将脚本代码与执行命令拼接成字符串传递。

以下是可正常工作的Windows Runner PowerShell实现:

name: Check Disk Space on Remote Hosts (Windows Runner)
on:
  push:
    branches:
      - main

jobs:
  check_disk_space:
    runs-on: windows-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Check Disk Space on Remote Hosts
        shell: powershell
        run: |
          # 配置参数(可替换为GitHub Actions inputs)
          $remoteHosts = "80.240.24.193,80.240.24.194".Split(",")
          $mountPoints = "/tmp"
          $minFreeSpace = "5"
          $user = "root"
          $scriptPath = Join-Path $env:GITHUB_WORKSPACE "check_disk_space.sh"

          foreach ($eachhost in $remoteHosts) {
            Write-Host "Checking disk space on $eachhost..."
            # 核心逻辑:将本地脚本通过管道传给远程bash -s,同时传递参数
            Get-Content -Raw $scriptPath | ssh -q -t "$user@$eachhost" "bash -s --" "$mountPoints" "$minFreeSpace" "$eachhost"
            
            # 检查ssh执行状态,远程脚本报错时标记步骤失败
            if ($LASTEXITCODE -ne 0) {
              Write-Error "Disk space check failed on $eachhost"
              exit 1
            }
          }

关键说明

  • 用Get-Content -Raw $scriptPath读取本地脚本完整内容,通过管道|传给ssh命令,和Linux上的< ./check_disk_space.sh效果完全一致,远程bash -s会从标准输入读取脚本并执行。
  • bash -s --后直接跟参数,这些参数会被远程脚本作为$1、$2、$3接收,和Linux Runner上的逻辑完全匹配。
  • 移除了错误的Here-String拼接逻辑,避免引号转义与空格解析问题。
  • 添加$LASTEXITCODE检查,确保远程脚本报错时,GitHub Actions步骤同步标记失败。

额外注意事项

  1. GitHub托管的Windows Runner默认已安装OpenSSH客户端,无需额外安装。
  2. 需配置免密登录(比如通过GitHub Secrets存储私钥,在步骤中加载到~/.ssh目录),避免执行时需要输入密码。
  3. 若要替换为GitHub Actions的inputs,直接将硬编码值替换为对应变量即可,示例:
    $remoteHosts = "${{ inputs.remote_hosts }}".Split(",")
    $mountPoints = "${{ inputs.mount_points }}"
    $minFreeSpace = "${{ inputs.min_free_space }}"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:16:52