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

如何让Shell脚本在PowerShell的gcloud CLI中正常运行?

问题根源

你写的是Bash shell脚本,Cloud Shell默认使用Bash环境所以能正常运行;但PowerShell有独立的语法体系,两者语法不兼容,直接执行就会触发解析错误,比如:

  • Bash的for ... in ...循环格式,PowerShell不识别,它需要foreach ($变量 in 集合)的写法
  • Bash的if [ 条件 ]判断逻辑,PowerShell要用if (条件),且比较运算符是-eq而非=
  • Bash里的echo命令,PowerShell对应Write-Host(或直接输出内容)
适配PowerShell的脚本

把原脚本改成PowerShell兼容版本:

# 获取当前凭证可访问的所有项目ID
$PROJECTS = gcloud projects list --format="value(projectId)"

# 遍历每个项目
foreach ($PROJECT in $PROJECTS) {
    Write-Host "Project: $PROJECT"
    # 检查Compute Engine服务是否启用
    $ENABLED = gcloud services list --project=$PROJECT --filter=config.name=compute.googleapis.com --format='value(state)'
    # 判断服务状态
    if ($ENABLED -eq "ENABLED") {
        # 列出无关联实例的磁盘信息
        gcloud compute disks list --project=$PROJECT --filter="-users:*" --format="csv(name,sizeGb,zone,status,type,lastAttachTimestamp,lastDetachTimestamp)"
    }
}
运行步骤
  1. 先确认PowerShell里gcloud CLI已配置好,可执行gcloud auth list验证身份
  2. 将代码保存为.ps1文件(比如Get-Disks.ps1)
  3. 在PowerShell中运行:.\Get-Disks.ps1
    • 如果遇到执行策略限制,可临时执行Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser来允许运行本地脚本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:05:17