If A or B equals C

Hi All,

I was writing a function today where I need the outcome to be true if A or B equal C, where see is the results of a Get-ItemProperty

Originally I had:

If $a -eq Get-ItemProperty…

Of course in order to avoid running the Get-ItemProperty cmdlet twice (due to needing to comapre it against $b as well) I have assigned the results to variable $C for use in the if statement.

Normally I would write this If A equals C or If B Equals C but was wondering, is there is a way to structure this as If A or B equal C?

Not really a big deal I was just curious if it were possible.

Thanks

Yep, more or less. :slight_smile:

$a = 1
$b = 3

$value = 1
if ($value -in $a, $b) {
    "it's either $a or $b, not sure which"
}

Thanks Joel, appreciate you taking the time to reply, I will make a note of the example as it may come in handy in the future.

Thanks again.

You could use the fact that -eq works differently with arrays, and returns the item if it’s in the list.

$a,$b,$c=1,2,2

$a,$b -eq $c
2

if ($a,$b -eq $c) { 'yes' }
yes

$a,$b,$c=1,2,3

$a,$b -eq $c
# null

if ($a,$b -eq $c) { 'yes' }

There is a kind of “or” regex too.

$c -match "$a|$b"

Yep, definitely possible. I’d probably not want to do the first one there if the array is fairly large, it’d make PS do a lot of extra work (building a whole new array, etc.) that isn’t needed in this instance.

Good call on -match, but important to remember it only works if your values are strings, or can be accurately represented when converted to strings.

Hmm, somehow with foreach there’s no extra memory being used (the WS doesn’t go up). And I used to correct people on this.

foreach ($i in 1..10000000) { $i;sleep 1}


# another window
ps powershell

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    554      29    78136      88100       1.27   2848  59 powershell
    577      29    62704      73232       3.63  11460  59 powershell

Yeah, foreach just accesses each item in the array in turn, so it won’t use much, if any, extra memory. However, creating a new array does create some overhead in terms of extra memory (the amount will of course still vary based on the sizes of the arrays involved and what they contain).