1

For example, in BASH I can write:

# if foo is empty, it will equal 'bar'
foo=${foo:='bar'}

How would I do that in powershell? Ideally, I can set a parameter's default value to an environment variable that defaults to a literal, written for communication purposes in pseudo code:

param(
  $foo=${env:foo:='bar'} # in pseudo code
)

How does powershell handle this situation?

2
  • 1
    Does this answer your question? Set PowerShell variable with environment variable or a default if not present Commented Oct 16, 2023 at 17:03
  • if you want to handle the condition inside the param block, you would need to use $(...) i.e.: param($foo = $( <# condition inside #> ).... personally wouldn't recommend that, much better to handle this in the blocks. I believe Abdul's link answers this otherwise Commented Oct 16, 2023 at 17:11

1 Answer 1

2

In Windows PowerShell:

param(
  $foo = ($env:foo, 'foo')[$null -eq $env:foo]
)

Note:

  • This takes advantage of the fact that when a Boolean expression such as $null -eq $env:foo is used as an array index, $true is coerced to 1, and $false to 0, so that the appropriate array element is returned.

    • Note: It is not a concern here, but due to use of an array literal, all array elements are evaluated up front, before the element of interest is extracted.
  • The conceptually clearer (and short-circuiting), but more verbose alternative is to use a regular if statement, which, however, requires enclosure in $(...), the subexpression operator:

    param(
      $foo = $(if ($null -eq $env:foo) { 'foo' } else { $env:foo })
    )
    

In PowerShell (Core) 7+, you can use ??, the null-coalescing operator:

param(
  $foo = $env:foo ?? 'foo'
)
Sign up to request clarification or add additional context in comments.

Comments

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.