Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a dataset in PowerShell?

Tags:

I am trying to output values of each rows from a DataSet:

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

gives the 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?

like image 824
Murtaza Mandvi Avatar asked Apr 29 '09 20:04

Murtaza Mandvi


1 Answers

The PowerShell string evaluation 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 -lt $ds.Tables[1].Rows.Count;$i++) {    write-host "value is : $i $($ds.Tables[1].Rows[$i][0])" } 

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

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows) {    write-host "value is : $($Row[0])" } 
like image 178
Steven Murawski Avatar answered Sep 17 '22 11:09

Steven Murawski