How can I set a variable in a conditional statement?
Unfortunately PowerShell doesn't have a conditional assignment statement like Perl ($var = (<condition>) ? 1 : 2;
), but you can assign the output of an if
statement to a variable:
$var = if (<condition>) { 1 } else { 2 }
Of course you could also do the "classic" approach and assign the variable directly in the respective branches:
if (<condition>) { $var = 1} else { $var = 2}
The second assignment doesn't supersede the first one, because only one of them is actually executed, depending on the result of the condition.
Another option (with a little more hack value) would be to calculate the values from the boolean result of the condition. Negate the boolean value, cast it to an int and add 1 to it:
$var = [int](-not (<condition>)) + 1
In Powershell 7 you can use the ternary operator:
$x = $true ? 1 : 2echo $x
displays 1
.
What you may want however is switch
, e.g.,
$in = 'test2'$x = switch ($in) {'test1' {1}'test2' {2}'test3' {4}}echo $x
displays 2
.
A little example that can help to understand.
PowerShell script:
$MyNbr = 10$MyMessage = "Crucial information: " + $( if ($MyNbr -gt 10) { "My number is greater than 10" } elseif ($MyNbr -lt 10) { "My number is lower than 10" } else { "My number is 10" })Write-Host $MyMessage
Output:
Crucial information: My number is 10
If you change the MyNbr variable, you will have a different result depending on conditions in the if statements.