Is it possible break out of a Foreach loop?

This topic contains 6 replies, has 4 voices, and was last updated by  Ramon Tan 1 week ago.

  • Author
  • #102544

    Ramon Tan

    Consider the ff. lines of code:
    Import-Csv $f | Select-Object -Property FName,GrossPay |
    Foreach-Object -Process { $z = $_.FName.CompareTo("")
    If ($z -NE 0) { ... do a whole bunch of things }
    The imported CSV file (which is small) is always fixed at 200 lines (i.e., records).
    Each line/record is 100 bytes. But the typical actual data is just 30%, with the remaining 70% blank all the time.
    In the above code, the comparison test in the variable ($z) signals the logical "end of file", (an empty FName string)
    but the processing continues until the last line/record.
    Is there a PS syntax to break out of a script block — such as the one above — in order to save further unnecessary
    processing of empty records? Another related question: is there a named constant variable similar to $TRUE, $FALSE
    for checking an empty string? I tried using $NULL but failed.

    Would be grateful for any advice, help or references on this issue.
    Many thanks.

  • #102547

    Don Jones

    The “break” keyword will exit a loop.

    • #102557

      Ramon Tan

      Many thanks Don, much appreciated.

  • #102548

    James Crompton

    As Don said you can use the break keyword like this:

    Import-Csv $f | Select-Object -Property FName,GrossPay | Foreach-Object -Process `
        $z = $_.FName.CompareTo("")
        if ( $z -eq 0 )
            #... do a whole bunch of things 

    you could also filter out the values without a value before you start the foreach loop with the where clause:

    Import-Csv $f | where Fname -ne "" | Select FName,GrossPay | Foreach `
     #... do a whole bunch of things }
    • #102559

      Ramon Tan

      Thanks Mr Crompton for this wealth of information, offering numerous insights and giving me an increased understanding on how to use PS's features. The second solution, to filter them early on at the CSV file stage, seems the smartest! Much thanks.

  • #102604

    Joel Sallow

    To add a little to this, you can break out of specific loops, as well. For example:

    :outer foreach ($Outer in 1..250) {
        :middle foreach ($Middle in 1..100) {
            foreach ($Inner in 1..50) {
                $Case = ($Outer * $Inner * $Middle) % 19
                switch ($Case) {
                     1 {break}
                     5 {break middle}
                     7 {break}
                     11 {break middle}
                     18 {break outer}
                     default { Write-Output "$Inner - $Middle - $Outer" }
    • #102610

      Ramon Tan

      Many thanks Mr Sallow, your tips are very useful to me.
      Much appreciated.

You must be logged in to reply to this topic.