How can I set a variable in a conditional statement?

26,127

Solution 1

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

Solution 2

In Powershell 7 you can use the ternary operator:

$x = $true ? 1 : 2
echo $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.

Solution 3

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.

Share:
26,127
Charles
Author by

Charles

Security Analyst for a large firm. Work with a little bit of everything, hardware, software, admin, DBs, Python, PowerShell, HTML, JavaScript, PHP and if i dont, eventually ill have to learn ;)

Updated on August 06, 2022

Comments

  • Charles
    Charles over 1 year

    I have a script that checks the health of a pc by parsing through log files looking for indicators of compromise. If the script finds a certain event id it returns a normalized message. The end goal is to do math on these returns- this will generate a health score for that PC.

    What I need to know is how set a variable (say X with a value of 1) if the event id is found, and set the same variable (say X with a value of 2) if the event id is not found. If I just set both variables in the script -in their respective if/else blocks, won't the last variable always overwrite the first regardless of the condition?

  • Charles
    Charles over 8 years
    Thanks- this makes sense. for this use case just declaring the var in the separate blocks will work fine I believe. Thanks again for the clarity!