0

I have 2 arrays like this:

$array1 = @('Item10', 'Item20', 'Item30', 'Item40')

$array2 = @('Item1', 'Item3')

I would like to have my final array like this:

$arrayfinal = @('Item30', 'Item40')

meaning: find 'like' Item1 from array2 in array1, so remove it !

I tried: with the '-like' operator, the '-ne' operator, tried to add '*' and use the 'like' operator but could not find what I want.

Thanks for your help

1
  • I'm having problems following your question due to the example you give.. Both arrays have no element in common, so why you would end up with just the last two elements of $array1 is beyond me.. Commented Feb 4, 2022 at 12:38

1 Answer 1

1

You need to test each value in $array1 against each possible prefix from $array2 until you get a match (or not) - in other words, nested filters.

My preferred approach is to nest .Where({...}, 'First') inside Where-Object:

$arrayfinal = $array1 |Where-Object {$item = $_; -not $array2.Where({$item -like "${_}*"}, 'First')}

The 'First' mode will make .Where() return as soon as the first item satisfies the condition, thereby not needlessly going through all of $array2 on each iteration.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems the OP wants to retain only the elements of $array1 which are NOT like elements in $array2, so the negation should be added in front of the filter condition: $arrayfinal = $array1 |Where-Object {$item = $_; ! $array2.Where({$item -like "${_}*"}, 'First')}
@Alex Thanks, I got it mixed up because of OPs impossible final array example. Fixed

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.