Link to home
Start Free TrialLog in
Avatar of huangs3
huangs3Flag for Canada

asked on

How to user SQL Server Powershell to run a query and return the results to Powershell script scope?

Hi Experts,

I am try to write a Powershell script to:
1. run on my desktop and query a remote database; and
2. return the rows to the scope of Powershell script for analysis

I wrote a test script using SQL Server Powershell as below
Set-ExecutionPolicy Bypass
Import-Module “sqlps” -DisableNameChecking
Invoke-Sqlcmd -Query "select top 10 * from schemaname.tablename" -ServerInstance "instancename" -Database "dbname" -Username "username" -Password "password"

Open in new window


It successfully connects to database and run the query, but displays the query result on the screen in some text format. How can I retrieve the result in some kind of objects in Powershell, such that I can do some analysis such as
Count the number of records?
Check some field values of some records?


From MSDN documentation Invoke-Sqlcmd I can only find that the output can be redirected to stderr. With some trick it maybe to some text file. However, this is not convenient. Is there any other possibility to get the returned data stored in nice collection objects in Powershell?

Thank you!

Below is the environment I am working with:
Remote database: SQL Server 2012
Powershell version on desktop: 4.0
SQL Server Management Studio on desktop: 2014
Desktop OS: Win 7
ASKER CERTIFIED SOLUTION
Avatar of DBAduck - Ben Miller
DBAduck - Ben Miller
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of huangs3

ASKER

Thank you!