Question

I am converting a text file to a csv that I currently hold in memory until the very end of my edits. I mark each row with either a 4 or 6. I get to a point where I loop through the table row by row. If it has a 6 I do one thing, and a 4 I do something else. It will be something like,

6, 4, 6, 4, 4, 6, 4, 4, 6

With any number of 4's between each 6. To keep track of the 4's I have a counter that counts them. I also have a counter that counts each row. The problem comes when I want to specify a row by the rowCounter. I want to be able to do something like $rowCount - 1 when I get into a 6 and fourCount is not zero. So that I can output the data to the 4 row above it.

$fourCount = 0
$rowCount = 0
foreach($row in $ResultsTable){
  if ($row.'RowType' -eq 6) {
    if ($fourCount -gt 0) {
      #Sort-Object {$row.'CheckDate'} -descending
      $remainAmount = $currentAmount - $checkAmount
      Write-Host "Counter no longer 0, resetting counter"
      $currentAmount = @()
    }
    $checkAmount = $row.'check'
    Write-Host "This line starts with 6"
    $rowCount = $rowCount + 1
  } elseif ($row.'RowType' -eq 4) {
    $currentAmount += $row.'check'
    $rowCount = $rowCount + 1
    $fourCount++
    Write-Host "This line starts with 4"
  } else {
    Continue
  }
}

Here is how I populate each row of the CSV

$files = Get-ChildItem $source *.txt
$content = Get-Content $files

foreach ($line in $content) {
  if ($line.StartsWith("6")) {
    $output = $ResultsTable.Rows.Add($line.Substring(0,1), $line.Substring(1,3), $line.Substring(4,3), $line.Substring(7,10), $line.Substring(17,20), $line.Substring(37,8))
  } elseif ($line.StartsWith("4")) {
    $cleanInvNum = $line.Substring(11).Replace("-A", "")
    $output = $ResultsTable.Rows.Add($line.Substring(0,1), $line.Substring(1,3), $line.Substring(4,3), " ", " ", " ", $cleanInvNum, " ")
  }
}

Does anyone know how to do this?

Était-ce utile?

La solution

Per the comments, you need to go back to the original collection you're getting your loop enumerator from and reference that row as:

 $ResultsTable.Rows[$rowCount] 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top