coderdad coderdad - 2 years ago 530
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"

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download