0

I have two list, A and B and I needed the element of the B list not present in the A list to be in a created list C in Powershell. (list or array)

A B C
One One Second
Two Two
Three Three
Third Second
Fourth third

In this example in C there is the word Second as it is not present in A list. So it is not the difference between two list, it is one to another, but not the other way around.

I have tested the Compare-Object command but it will exclude the element that are not in B but in A and the ones that are in B but not in A. Which is not what I am looking for. I also tried something like this :

foreach ($elem in $A) { if ($B -contains $elem) { "there is a match" } }

But it didn't work as I want.

I'm a bit lost a this point.

Noemie
  • 121
  • 1
  • 9
  • Does this answer your question? [Comparing two arrays & get the values which are not common](https://stackoverflow.com/questions/6368386/comparing-two-arrays-get-the-values-which-are-not-common) – iRon Mar 31 '21 at 13:28

2 Answers2

1

Use the -notin operator:

$C = @($B) -notin $A

Supplying an enumerable left-hand operand to a scalar comparison operator like -notin turns the operator into a filter - and suddenly it works just like $B |Where-Object { $_ -notin $A }

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Not sure what I'm doing differently, but I am not seeing that behavior. When I do `@($B) -notin $A` I just get `True` – Daniel Apr 01 '21 at 04:51
0

So finally I decided to use the following command:

Compare-Object -IncludeEqual -ReferenceObject $A -DifferenceObject $B

With the side indicator, I could manage my third table the way I want.

Noemie
  • 121
  • 1
  • 9