Home > Net >  Unexpected log executing inside a foreach loop
Unexpected log executing inside a foreach loop

Time:01-17

I'm looping through lines of text in a Typescript file using a foreach loop, and adding the line to an array if it matches a condition. After exiting the loop I echo the length of the resulting array. Logging the length of the array to the console executes once per loop iteration, instead of once after the loops finishes.

My code is the following

        # $enumfilepath is the path of the file containing the variables
        $enumfile = Get-Content $enumfilepath
        [System.Collections.ArrayList]$vars_array = @()

        foreach ($line in $enumfile) {
                $line = $line.Trim()
                if (($line -like "*=*") -and !($line -like "//*")) {
                        $var, $vars_ref = $line -split "="
                        $vars_array.Add($var)
                }
        }
        Write-Output "nº of total vars $(@($vars_array).Length)"

And the console log:

... (not showing all output, starting from zero as expected)

442

443

444

nº of total vars 445

--- EDIT --- I just noticed the problem is not with the logging line. Commenting out that line (and having not other echo's in the script) also logs the 444 iteration lines.

CodePudding user response:

ArrayList.Add() outputs the index at which the new item was added.

You can either suppress the output from that call with [void], Out-Null, or by assigning it to the special $null variable:

[void]$vars_array.Add($var)
# or
$vars_array.Add($var) |Out-Null
# or
$null = $vars_array.Add($var)

Alternatively, use a collection type that doesn't have the same annoying side effect:

[System.Collections.Generic.List[psobject]]$vars_array = @()
  • Related