Skip to content
Advertisement

Poweshell retrieve sql query result

I am quite new to PowerShell. I have multiple SQL queries which I am executing from a PS script using SQL adapter. I need to retrieve the common results based on a column from the queries without changing existing queries or writing another one. How to achieve this with PowerShell using the results stored in a variable? I’ve tried working around with rows[x],columns[y] but it doesn’t work and writing the names of the columns every time is difficult for big results.

I am storing the results this way:

Suppose query 1 results:

query 2 results:

I need the common one’s from both results based on the names column which I will further save in a file. (Edited the output as it wasn’t in right format)

Advertisement

Answer

In general, PowerShell’s Group-Object coupled with array indexing can achieve this goal.

Results0.csv will contain the first table results. Results1.csv will contain the second table results.

Group-Object groups objects based on grouped properties. Grouping on names will put all objects with the same names value into a GroupInfo object accessible by the Group property. The Group property is a collection with indexed items. The first item in each grouping ([0] item) will be the first object read. So as long as $q1 and $q2 share a value, then [0] item will always be from $q1 because we send $q1 into the pipeline first from expression $q1 + $q2. Correspondingly, [1] will contain $q2 items.


Edit 1: You updated your question with table column names with a different requirement.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement