Source Code and Samples

Friday, 2 February 2007

Returning Results from SQL as a Table


A great powershell script from "Greg" that shows how to produce tabulated results from a SQL query.

Source Code

function Get-Sql {
param ([string]$conn, [string]$sql)

# setup connection
$connObj = new-object System.Data.SqlClient.SqlConnection
$connObj.ConnectionString = $conn
# setup command $cmdObj = new-object System.Data.SqlClient.SqlCommand $cmdObj.Connection = $connObj
$cmdObj.CommandText = $sql
$reader = $cmdObj.ExecuteReader()
while ($reader.Read()) {
$result = new-object System.Management.Automation.MshObject
for ($i=0;$i -lt ($reader.FieldCount) ;$i++) {
$fld = new-object System.Management.AUtomation.MshNoteProperty $reader.GetName($i), $reader[$i] $result.MshObject.Members.Add($fld); }
$connectionString = "Server=(local);Database=AdventureWorks;Integrated Security=SSPI"
$sqlText = "select top 10 * from Person.Contact"
Get-Sql $connectionString $sqlText format-table

1 comment:

Leslie Lim said...

This is a great website, so many people need this information, thanks for providing it.