Reputation: 3698
I am trying to set a variable in a PowerShell script from either an Environment Variable or a default if the $env
value isn't specified. I can do something similar in Bash by doing the following.
BASH_VAR_IN_SCRIPT=${MY_ENV_VAR:="default value"}
Is there something similar in PowerShell? My Google-fu isn't returning what I am looking for. I am using PowerShell Core 7.
Upvotes: 3
Views: 4500
Reputation: 1123
$env:MY_ENV_VAR
will return null
if MY_ENV_VAR
isn't defined, so you can use the null-coalescing operator ??
to specify a default value:
$myVar = $env:MY_ENV_VAR ?? "default value";
This only works in Powershell 7+. For older versions, you can use an if-statement:
$myVar = if ($env:MY_ENV_VAR) { $env:MY_ENV_VAR } else { "default value" };
Upvotes: 11