Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Charles Avatar asked Sep 11 '15 04:09

Charles


1 Answers

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
like image 194
Ansgar Wiechers Avatar answered Sep 21 '22 13:09

Ansgar Wiechers