Monday, January 19, 2009

Recordset to Powershell object collection

I've found this pretty damn useful: it converts an ADO.Net IDbDataReader into a collection of powershell objects, mapping column names to property names so you can sort and filter and whatnot using standard PS syntax.

# Executes an IDbCommand and converts the resultset
# to a Powershell object collection
function ExecuteCommand(
$command = { throw 'Command must be supplied' }
$rows = @();
$reader = $command.executereader()
$values = new-object object;

for($i = 0; $i -lt $reader.FieldCount; $i++){
$name = $reader.GetName($i);
$value = $reader.GetValue($i);

Add-Member -in $values noteproperty $name $value
$rows+= $values;

Next week: why I was doing this in the first place (much more interesting)

1 comment:

Anonymous said...

Usefull post, thanks

Popular Posts