cyberbemon
cyberbemon

Reputation: 3190

Extract data from System.Data.DataRow in PowerShell

I have a PowerShell script that executes a SQL command and returns a list of ID numbers.

When I iterate through the list, this is what it returns.

System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow

I tried adding Out-String to my list,

$q_result = $db.ExecuteWithResults($int_cmd2)
$table = $q_result.Tables[0] | Out-String

foreach ($user_info in $table)
{
    write-host $user_info 
}

but that returns a poorly formatted list of numbers, everything is tabbed to the far right:

                                                                                                      GroupID
                                                                                                      -------------
                                                                                                                381
                                                                                                                382
                                                                                                                383
                                                                                                                384
                                                                                                                385
                                                                                                                386

I tried using, $user_info.Item[0] in the loop, but that returns nothing.

How can I extract just the numbers from the list?

Upvotes: 25

Views: 63451

Answers (3)

Dominic Flynn
Dominic Flynn

Reputation: 71

Assuming the column name is GroupID

$sql = "SELECT [GroupID] FROM theTable"
$table = Invoke-SQLCmd -Query $sql -ServerInstance $sqlServerInstance -Database $database -OutputAs DataRows

foreach($user_info in $table)
{
    $user_info.GroupID
}

or

foreach($user_info in $table.GroupID)
{
    $user_info
}

Upvotes: 4

zstefanova
zstefanova

Reputation: 1831

You can also use ItemArray. Prints the entire row, while Item(index) prints the values from the indexed cell.

enter image description here

Upvotes: 36

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Item is a parameterized property, not a list you can index into:

foreach($row in $table)
{
    $row.Item("GroupID")
}

or (assuming that "GroupID" is the first column):

foreach($row in $table)
{
    $row.Item(0)
}

Upvotes: 25

Related Questions