Opening Databases from PowerShell

by Dec 18, 2009

The easiest way of accessing databases right from PowerShell is to visit control panel and open the Data Sources (ODBC) module (which resides in Administrative Tools inside control panel). Use the GUI to set up the database type by clicking the "User DN" or "System DN" tab and then click Add. Remember to write down the "Data Source name" you assign because that's the only thing PowerShell is going to need.

You should next use this code (replace "myDataSource" with the data source name you assigned, and replace TableName with the table name inside your database you want to display):

$objConnection = New-Object -comobject ADODB.Connection
$objConnection.Open("myDataSource")

$objRS = $objConnection.Execute("SELECT * FROM TableName")
while ($objRS.EOF -ne $True) {
foreach ($field in $objRS.Fields) {
'{0,30} = {1,-30}' -f $field.name, $field.value
}
''
$objRS.MoveNext()
}

Twitter This Tip! ReTweet this Tip!