jshizzle
jshizzle

Reputation: 487

If statement - Four variables, only run if one true

I have the following which doesn't allow both variables to be enabled (boolean true value):

If (($Variable1) -and ($Variable2)) {
   Write-Warning "Both variables have been enabled. Modify script to enable just one."
   Pause
   Break
}

This works great, however, how would I ensure only one is ever enabled when 4 possible variables exist? I'm thinking a combination of -and & -or?

Upvotes: 0

Views: 1040

Answers (2)

whatever
whatever

Reputation: 891

You can add the boolean values and check their count:

If (([bool]$Variable1 + [bool]$Variable2 + [bool]$Variable3) -ne 1) {
    ...
}

but of course you have to make sure that these can actually be cast to boolean.

That's what "exclusive or" (xor) is for:

If ($Variable1 -xor $Variable2 -xor $Variable3) {
    ....
}

About logical operators in Powershell

Upvotes: 3

arco444
arco444

Reputation: 22841

Cannot think of a way to do this that avoids using a counter. You have to check the value of each variable and keep count of how many are $true.

$trueCount = 0
($variable1, $variable2, $variable3, $variable4) | % { if ($_ ) { $trueCount++} } 

if ($trueCount -eq 1) {
  write-host "only one variable true"
}
else {
  write-host "condition not met"
}

Upvotes: 3

Related Questions