Connecting to a SQL Database

As I have been migrating over my scripts from VBScript to PowerShell I have had to convert over several scripts.
One example of this is a section of code that I use to pull data from Tables in SQL databases.
This code assumes you are using SQL authentication credentials.

#Authentication Strings
$account = “user”
$pw = “password”
$table = “table or view”
$db = “sql database”
$server = “sql server”

# Specify SQL Query
$SqlQuery = “Select * From $table”

# Create SQL connection object
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

#Set the ‘Connection String’ property
$SqlConnection.ConnectionString = “Server = $server; Database = $db;user = $account; password = $pw”

# Create SQLCommand object
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

#Set SQLCommand Text property (SQL Query)
$SqlCmd.CommandText = $SqlQuery

#Set the Connection property
$SqlCmd.Connection = $SqlConnection

#Create SQL Adapter repository
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter

#Run SQL Connection
$SqlAdapter.SelectCommand = $SqlCmd

#Create SQL DateSet object
$DataSet = New-Object System.Data.DataSet

#Populate $DataSet with Connection results
$nRecs = $SqlAdapter.Fill($DataSet)
$nRecs | Out-Null

#Populate Table object with required Table
$ objTable = $DataSet.Tables[0]

#Parse through the rows
ForEach($objRow In $objTable)
{
#Echo Column Names
Write-Host $objRow.column
}

In the above code you will need to supply replacements for, $account, $pw, $table, $db and $server. Depending on the database you are connecting to and the structure of the table you will want to modify the contents of $SqlQuery (SQL query string) and the $objRow.column would need to be changed to a valid column name for the table you are querying against.

I hope this helps.

All information is provided on an AS-IS basis, with no warranties and confers no rights.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s