How to logical OR multiple variables in Powershell

Viewed 97

I thought this was simple. And I'm sure it is. But, I can't seem to crack it.

I have 3 functions that return a true or false value.

In a later if evaluation I am trying to logical or the 3 results together.

Something like this:

if (Fnc1 -or Fnc2 -or Fnc3) { write-host "Yes" }

Not only is Powershell highlighting the syntax differently for the first Fnc1 from the others, it's only returning true or false based on the value of Fnc1 from what I can tell.

I know this works:

if ((Fnc1 -eq $true) -or (Fnc2 -eq $true) -or (Fnc3 -eq $true)) { write-host "Yes" }

But, that seems like overkill and un-necessary.

What am I missing?

2 Answers

PowerShell attempts to parse the -or token as a function parameter when you place it after a function name like that. Surround each function call in ():

if ((Fnc1) -or (Fnc2) -or (Fnc3)) { write-host "Yes" }

another way to get that is to use the -contains collection operator. lookee ...

function Get-True {$True}
function Get-False {$False}


@((Get-True), (Get-False), (Get-True)) -contains $True

output = True

if all those were Get-False, the result would be False.


note that this method requires that all the function calls be run before the -contains operator can test anything. that means the -or solution would be more efficient since that would run each function call in sequence and stop when the -or was satisfied.

the -or solution can be much more efficient if the function calls take any significant amount of time or resources.

thanks to @SagePourpre for pointing that out. [grin]

Related