11

I'm stuck with my script. I need to compare two arrays, one is the result of a query, the other one of a content of a file:

$Array1 = Invoke-Sqlcmd -Query "select name from person"

$Array2 = Get-Content ".\Myfile.txt" #the file is a set of one item
every line

Now, in $Array2 there are items that I would like to delete from the $Array1.

How can I do this? Thank you for yr help!

3 Answers 3

26

Use the Where-Object cmdlet to filter $Array1 based on what is in $Array2:

$Array1 = @($Array1 |Where-Object { $Array2 -notcontains $_ })

That works if Invoke-Sqlcmd returns simple strings. If not, you could do something like:

$Array1 = @($Array1 |Where-Object { $Array2 -notcontains $_.someProperty })
Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind, if the array items are strings, and this filter returns a single item, you will get unexpected results iterating through the resultant array as each item will be individual characters of the string instead of a single array of one string. To fix this, cast the whole line to [Array]. Example: $filtered = [Array]($a | Where { $b -notcontains $_ })
3

If performance is an issue, you can get faster results constructing an alternating regex from one of the arrays, and using it as an array operator against the other.

$Array1 = Invoke-Sqlcmd -Query "select name from person"

$Array2 = Get-Content ".\Myfile.txt" #the file is a set of one item
every line

$regex = ‘(?i)^(‘ + (($Array2 |foreach {[regex]::escape($_)}) –join “|”) + ‘)$’

$Array1 -notmatch $regex

Explanation of the code to build the regex here.

Comments

1

Or with an arraylist, there's a Remove (or RemoveAt) method (case sensitive):

$array2 = 1,2,3
[collections.arraylist]$array = 1,2,3,4,5,6

$array2 | % { $array.remove($_) }
$array

4
5
6

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.