0

Given arrays of

$requiredElements = @('Valid1', 'Valid2')
$elementsGood1 =  @('Valid1', 'Valid2')
$elementsBad1 = @('Valid', 'Invalid')

I can get back an array of booleans like this

$requiredElements.Foreach({$_ -in $elementsGood1})

But what I am struggling with is evaluating that array with -and. I can do it as a loop, but I would like to do it with the built in .NET methods if at all possible, so something like

$value = $true
$requiredElements.Foreach({$_ -in $elements}).Foreach({$value = $value -and $_})

But of course that's just pseudo code because I am not actually passing in the initial value or getting it back out. What I hope is that there is some .NET way to do a logical operator on an array of bool. Or perhaps a way to recursively inject the running value back into the final loop. It's a very academic question, but I feel like if there is an answer it will provide an approach that is useful in other situations. This is just the most simplified example I can come up with as a question.

The "long" form that works is

$value = $true
foreach ($item in $requiredElements) {
    $value = $value -and ($item -in $elementsBad1)
}
$value

I am just trying to replicate this as chained method calls if at all possible.

9
  • 1
    Afaik, this question is just a duplicate of If all values in 'foreach' are true, meaning: -not ($requiredElements -ne $value) Commented Mar 18, 2024 at 7:49
  • 1
    Wait, now it's making more sense. This seems to do the job for required. -not($requiredElements.Foreach({$_ -in $elementsGood1}) -ne $true) Commented Mar 18, 2024 at 8:00
  • 2
    How about $requiredElements.Foreach({$_ -in $elementsGood1}) -notcontains $false? Commented Mar 18, 2024 at 8:05
  • 1
    @mklement0 Dammit, I hate when it's that obvious in hind sight! :) Commented Mar 18, 2024 at 8:29
  • 1
    @Gordon Do not be so hard on yourself. Feel the joy of having a new insight. (I realise this phrasing seems weird. I only attempt to put a more positive spin on this. It is not meant sarcastically.) Commented Mar 18, 2024 at 8:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.