0

I am trying to filter some tables from my database which exists in my solution folder. I want to filter all tables that I am pulling from SQL Server:

$existingTables = "Table1", "Table2", "Table3", "Table4"

#getting all tables except existing ones
#SqlQuery = "SELECT name FROM sys.Tables order by name asc"
$filteredTables = ((Invoke-SQL -DataSource $ServerName -DatabaseName $DatabaseName -UserID $UserID -Password $Password -SqlCommand $SQLQuery).name | ? {$_ -notcontains $existingTables})
#$filteredTables returns all tables, including the existing ones...

I've tried $_.name and it is the same result.

3
  • 4
    Why not add a where name not in() into the select statement? Commented Dec 5, 2018 at 11:59
  • 2
    $_ -notcontains $addedTables -> $addedTables -notcontains $_. You switched the operands. For -[not]contains the correct order is <reference_array> -notcontains <item>. Otherwise use -[not]in (<item> -notin <reference_array>). The latter is not available prior to PowerShell v3, though. Commented Dec 5, 2018 at 12:00
  • 1
    Should $addedTables be $existingTables? Commented Dec 5, 2018 at 13:15

1 Answer 1

2

You're using the operands of the -notcontains operator in the wrong order. The correct syntax is

reference_array -notcontains item

In your case:

$existingTables -notcontains $_

or

$existingTables -notcontains $_.Name

if you don't expand the property Name.

If you want to use the reference array as the second operand you must use the -notin operator:

$_ -notin $existingTables

However, that operator is not available prior to PowerShell v3.

Alternatively, you could add an exclude clause to your SQL statement, as @vonPryz suggested in the comments. Take care to not open yourself to SQL injection when doing that, though.

Don't do this:

$SQLQuery = @"
SELECT ...
FROM ...
WHERE name NOT IN ('$($existingTables[0])', '$($existingTables[1])', ...)
"@

Use a prepared statement (or "parameterized query" as Microsoft calls them). I don't recognize the cmdlet you're using, though (doesn't seem to be Invoke-Sqlcmd), so I can't tell you how to do it with that cmdlet.

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

1 Comment

It crossed on my mind that I replaced the order but I didn't try :) Thank you very much!

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.