Thursday, August 20, 2009

Connecting to SQL Server and running query

We have a small requirement, connect to SQL Server while in powershell and run a query. This can be done using below code

# Declare a table to hold the returned data
$out_table = new-object System.Data.DataTable
# Declare a connection to connect to sql server
$cn = new-object System.Data.SqlClient.SqlConnection("Data Source=BOLT\BOLT_TST2;Initial Catalog=master;Integrated Security=True")
# Declare an Adapter to connect and run the query
$qr = new-object System.Data.SqlClient.SqlDataAdapter("Select * from sysobjects where xtype='U'",$cn)
# fill the adapter with result
$qr.Fill($out_table)
# print the result
write-output $out_table | Format-Table


It's quite straightforward, you get the result in your powershell window.
Please note that this is not connecting using SMO (as discussed in other posts of this blog).

No comments:

Post a Comment