views:

3109

answers:

3

I am trying a "very" simple task to output values of each rows from a dataset :

$Data = '' for($i=0;$i -le $ds.Tables[1].Rows.Count;$i++)
{
write-host 'value is : '+$i+' '+$ds.Tables[1].Rows[$i][0]
}

OUTPUT :
value is : +0+ +System.Data.DataSet.Tables[1].Rows[0][0]
value is : +1+ +System.Data.DataSet.Tables[1].Rows[1][0]
value is : +2+ +System.Data.DataSet.Tables[1].Rows[2][0]
value is : +3+ +System.Data.DataSet.Tables[1].Rows[3][0]
value is : +4+ +System.Data.DataSet.Tables[1].Rows[4][0]
value is : +5+ +System.Data.DataSet.Tables[1].Rows[5][0]
value is : +6+ +System.Data.DataSet.Tables[1].Rows[6][0]

How do i get the actual value from the column ?!?!

A: 

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
zdan
zdan - close, but you should have double quotes around the whole string (single quotes don't allow evaluation). and you don't need the additional quotes or backticks (tough to tell which they are) in the string.
Steven Murawski
The evaluations are performed outside the single quotes and concatenated with the quoted strings which would be equivalent to enclosing the whole thing in double quotes. I agree that would be clearer, but I wanted to match his original question.
zdan
+4  A: 

The PowerShell string evalutation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -le $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally, the foreach keyword allows you to iterate through a collection or array without needing to figure out the length.

Rewritten -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host 'value is : $($Row[0])
}
Steven Murawski
+2  A: 

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)

}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

HTH

Shay Levy