【问题标题】:MissingEndParenthesisInMethodCall - checking if an environment variable is emptyMissingEndParenthesisInMethodCall - 检查环境变量是否为空
【发布时间】:2018-03-15 19:08:01
【问题描述】:

我正在尝试检查我的 PowerShell 脚本中的环境变量是否为空或未设置。该脚本在 Docker 容器中运行,如果定义了环境变量,则旨在提取新代码:

CMD if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { \
        Write-Host Git pull started; \
        PortableGit\bin\git.exe pull; \
    }; \

我收到一堆错误:

web_1     | At line:1 char:110
web_1     | + ... ence = 'SilentlyContinue'; if (-not ([string]::IsNullOrEmpty(env:UPDA ...
web_1     | +                                                                  ~
web_1     | Missing ')' in method call.
web_1     | At line:1 char:110
web_1     | + ... ue'; if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { Wr ...
web_1     | +                                            ~~~~~~~~~~~~~~~~~~~~~~
web_1     | Unexpected token 'env:UPDATE_FROM_GITHUB' in expression or statement.
web_1     | At line:1 char:110
web_1     | + ... ence = 'SilentlyContinue'; if (-not ([string]::IsNullOrEmpty(env:UPDA ...
web_1     | +                                                                  ~
web_1     | Missing closing ')' in expression.
web_1     | At line:1 char:110
web_1     | + ... ue'; if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { Wr ...
web_1     | +                                            ~~~~~~~~~~~~~~~~~~~~~~
web_1     | Missing closing ')' after expression in 'if' statement.
web_1     | At line:1 char:132
web_1     | + ... e'; if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { Wri ...
web_1     | +                                                                 ~
web_1     | Unexpected token ')' in expression or statement.
web_1     | At line:1 char:133
web_1     | + ... '; if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { Writ ...
web_1     | +                                                                 ~
web_1     | Unexpected token ')' in expression or statement.
web_1     | At line:1 char:134
web_1     | + ... ; if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { Write ...

我不知道如何从这里开始。这些错误似乎是多余的,但没有明确的起点。会不会跟 Docker 解析命令的方式有关系?

【问题讨论】:

    标签: powershell docker environment-variables


    【解决方案1】:

    PowerShell 变量,包括环境变量,必须始终使用 sigil $

    引用

    因此,env:UPDATE_FROM_GITHUB 必须是 $env:UPDATE_FROM_GITHUB

    要简单地测试环境变量是否已定义/是否具有值,您并不严格需要-not [string]::IsNullOrEmpty(...);相反,您可以利用 PowerShell 的隐式布尔转换

    • $null 或空字符串 被视为 $False
    • 和任何非空字符串$True

    把它们放在一起:

    CMD if ($env:UPDATE_FROM_GITHUB) { \
            Write-Host Git pull started; \
            PortableGit\bin\git.exe pull; \
        }; \
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2012-04-28
      • 2011-03-20
      • 2021-05-12
      相关资源
      最近更新 更多