Converting Database Records into PowerShell objects

When you access a database, the result is not automatically wrapped as objects so you cannot pipe the result into other cmdlets like Sort-Object or Group-Object. You can with PowerShell v.2. Here is a sample based on a previous tip (refer to the previous tip regarding general database access):

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

$objRS = $objConnection.Execute("SELECT * FROM Kunden")
while ($objRS.EOF -ne $True) {
$hash = @{}
foreach ($field in $objRS.Fields) {
$hash.$($field.name) = $field.value
}
#$hash
New-Object PSObject -property $hash
$objRS.MoveNext()
}

The point which you should review occurs inside the while loop. For each recordset, an empty hash table is created and then filled with the fields and field values. In PowerShell v.2, New-Object can convert a hash table into a real object, which is then output. As you see, all database records surface as real objects, and each table column becomes an object property.

Twitter This Tip! ReTweet this Tip!


Posted Dec 21 2009, 08:00 AM by ps1

Comments

Converting Database Records into PowerShell objects « whileloop wrote Converting Database Records into PowerShell objects « whileloop
on 03-15-2010 11:15 PM

Pingback from  Converting Database Records into PowerShell objects « whileloop

Episode 106 – SQL PSX with Chad Miller « PowerScripting Podcast wrote Episode 106 – SQL PSX with Chad Miller « PowerScripting Podcast
on 03-22-2010 10:01 PM

Pingback from  Episode 106 – SQL PSX with Chad Miller «  PowerScripting Podcast

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.