coderdad coderdad - 1 month ago 30x
PowerShell Question

Is there a shorthand for the IF statement in PowerShell?

In bash, I often did things like:

[ -z "${someEnvVar}" ] && someEnvVar="default value"

Instead of creating a full-fledge if statement:

if [ -z "${someEnvVar}" ]; then someEnvVar="default value"; fi

Is there a similar shorthand in PowerShell without creating a function or alias?

I'd rather not write the following in PowerShell:

if ("${someVar}" -eq "") {
$someVar = "default value"


If seems more readable to me, but you can use short circuit of OR (similar to BASH version):

$someVar = ""
[void]($someVar -ne "" -or ($someVar = "Default"))

$someVar #yields "Default"

$someVar = "Custom"
[void]($someVar -ne "" -or ($someVar = "Default"))

$someVar #yields "Custom"