Accessing an SQL Database with a Connection String

by Jul 21, 2015

In a previous tip we explained how you can construct the connection string to a SQL database. Whether you use this to create the connection string, or whether you create a connection string from scratch does not matter – provided you have a valid connection string to a database, then this example will illustrate how you can submit SQL commands to the database.

#requires -Version 2

# make sure this is a valid connection string to your database
# see www.connectionstrings.com for reference
$connectionString = 'Provider=SQLOLEDB.1;Password=.topSecret!;Persist Security 
 Info=True;User ID=sa;Initial Catalog=test;Data Source=myDBServer\SQLEXPRESS2012'

# make sure this is valid SQL for your database
# so in this case, make sure there is a table called "test"
$sql = 'select * from test'

$db = New-Object -ComObject ADODB.Connection
$db.Open($connectionString)
$rs = $db.Execute($sql)

$results = While ($rs.EOF -eq $false)
{
    $CustomObject = New-Object -TypeName PSObject
    $rs.Fields | ForEach-Object -Process {
        $CustomObject | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Value
    }
    $CustomObject
    $rs.MoveNext()
}
$results | Out-GridView

Twitter This Tip! ReTweet this Tip!