How to loop through a dataset in powershell? How to loop through a dataset in powershell? powershell powershell

How to loop through a dataset in powershell?


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])"}


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}


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])"