Continue while from nested loop

I have the following loop structure:

while ($reader.Read() -eq $true)
{
    $row = @{}
    for ($i = 0; $i -lt $reader.FieldCount; $i++)
    {
        if(something...)
        {
            #continue with while
        }
    }
    #do more stuff...          
}

      

Now, is there a way to continue from the loop for

with the next iteration of the outer loop while

without any break variable? So if "something is true," I don't want to go #do more stuff

, but instead do the next one $reader.read()

. Continue

proceeds only to the next iteration of the loop for

. Break

will break the loop for

.

+3


source to share


2 answers


Factoring the inner loop for a function can improve readability, depending on how confusing your variables are.

function processRow($reader) {
    $row = @{}
    for ($i = 0; $i -lt $reader.FieldCount; $i++)
    {
        if(-not something...) { return $null }
        # process row
    }
    $row
}

while ($reader.Read()) {
    $row = processRow $reader
    if ($row) {
        #do more stuff...          
    }
}

      



But if you want to do it directly, you can, because PowerShell flags the breaks:

:nextRow while ($reader.Read()) {
    $row = @{}
    for ($i = 0; $i -lt $reader.FieldCount; $i++) {
        if(something...) {
            #continue with while
            continue nextRow
        }
    }
    #do more stuff...          
}

      

+7


source


EDIT: Revised, recursive (and untested!) Solution, so your size might be different:



function doReader()
{
    while ($reader.Read() -eq $true)
    {
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++)
        {
            if(something...)
            {
                #continue with while
                doReader
                break;
            }
        }
    }
}
doReader
#do more stuff

      

0


source







All Articles