3

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.

1 Answer 1

13

$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" };
Sign up to request clarification or add additional context in comments.

1 Comment

I should've mentioned I was using PowerShell Core 7. I've added that to my question now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.