Home > Net >  Remove array from array in powershell
Remove array from array in powershell

Time:02-04

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

CodePudding user response:

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.

  •  Tags:  
  • Related