I'm trying to check whether an environment variable is empty or unset in my PowerShell script. The script is running in a Docker container, and intended to pull new code if an environment variable is defined:
CMD if (-not ([string]::IsNullOrEmpty(env:UPDATE_FROM_GITHUB))) { \
Write-Host Git pull started; \
PortableGit\bin\git.exe pull; \
}; \
I get a bunch of errors:
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 ...
I'm not sure how to begin here. The errors seem redundant, but there isn't a clear starting place. Could it have something to do with how Docker parses commands?
PowerShell variables, including environment variables, must always be referred to with sigil $
Therefore, env:UPDATE_FROM_GITHUB
must be $env:UPDATE_FROM_GITHUB
To simply test if an environment variable is defined / has a value, you don't strictly need -not [string]::IsNullOrEmpty(...)
; instead, you can take advantage of PowerShell's implicit Boolean conversion:
$null
or the empty string is considered $False
$True
To put it all together:
CMD if ($env:UPDATE_FROM_GITHUB) { \
Write-Host Git pull started; \
PortableGit\bin\git.exe pull; \
}; \
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments