0

How can I remove the items in $b from $a?

$a = "aa","bb","cc","dd","ee"

$b = "bb","dd"

Do you know a good solution?

Thanks!

4
  • What have you tried so far? Commented Oct 3, 2018 at 15:47
  • A foreach loop and comparing each line with if command. I think there should be an easier way. Commented Oct 3, 2018 at 15:49
  • Possible duplicate of Delete items in an array that are in another array Commented Oct 3, 2018 at 15:56
  • You've actually got two arrays of strings, I assume you didn't know this so couldn't find the answer using the search. I'm voting to close as a duplicate as this has been covered before. Commented Oct 3, 2018 at 15:58

1 Answer 1

0

The Compare-Object command is the easiest way of doing this, although it's not very robust, if this is for use in production you may want to roll a more thought-out solution.

$c = Compare-Object -ReferenceObject $a -DifferenceObject $b | ? SideIndicator -eq '<=' | Select -Expand InputObject

Another way which is quite similar but more readable in my opinion is:

$c = $a | ? {$_ -notin $b}

Another way would be using the Group-Object command, and selecting unique entries, but this will include ones which were in $b but NOT in $a.

$c = $a+$b | Group-Object | ? Count -eq 1 | Select -Expand Group

all of these methods will output:

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

Comments

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.