Charles
Charles

Reputation: 345

How can I set a variable in a conditional statement?

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?

Upvotes: 13

Views: 39163

Answers (4)

nevarDeath
nevarDeath

Reputation: 197

You actually can evaluate a condition and assign the result to a variable. It's the closest you get to a ternary operator in PowerShell. I find it makes it simpler to do complicated conditional statements. It makes it easier to read and change them. Here's an example:

$theEventIdIWant = 6000  
$eventId = 5000
$correct = $eventID -eq $theEventIdIWant
if($correct) {$true} else {$false}

Upvotes: 1

Jaro
Jaro

Reputation: 125

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.

Upvotes: 10

VouDoo
VouDoo

Reputation: 17

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.

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200303

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

Upvotes: 15

Related Questions