Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 387
coderdad Avatar asked Feb 06 '23 06:02

coderdad


2 Answers

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"
like image 90
Paweł Dyl Avatar answered Feb 08 '23 19:02

Paweł Dyl


I am afraid Powershell doesnt have such an elegant solution as C# have:

Exp1 ? Exp2: Exp3
msg = (age >= 18) ? "Welcome" : "Sorry";

But you could do something like this:

$someVar = if ("${someVar}" -eq "") { "default value" }
like image 24
Kirill Pashkov Avatar answered Feb 08 '23 18:02

Kirill Pashkov