Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array subtraction in PowerShell

I have an array of objects:

$people= @()
foreach ($person in $databaseOfGuests)
{
   $people += @{ "FirstName"=$person.FirstName; "LastName"=$person.LastName } 
}

Now I want to remove duplicates from $people, is it possible to do this in PowerShell? Something like:

$people = $people | Select -Uniq

I have two arrays $people1 and $people2, I need to get array of all people that are in $people1 but not in the $people2 and vise versa. Something like:

$peopleInPeople1ButNotInPeople2 = $people1.Substruct($people2)
$peopleInPeople2ButNotInPeople1 = $people2.Substruct($people1)

Is it possible to do it in one line in PS?

like image 860
edwin Avatar asked Sep 03 '26 07:09

edwin


1 Answers

Try this:

$people1 | ? {$_ -notin $people2}

or you can filter by property, like firstname or lastname:

$people1 | ? {$_.Firstname -notin $people2.Firstname}
  • the -notin operator is available on PS3 and above, for lower versions you can use -notcontains
like image 105
Avshalom Avatar answered Sep 05 '26 09:09

Avshalom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!