Author Posts

June 15, 2018 at 3:59 am

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.

June 15, 2018 at 4:12 am

The “break” keyword will exit a loop.

June 15, 2018 at 4:28 am

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 )
    {
        break;
    }
    else
    {
        #... 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 }
}

June 15, 2018 at 5:00 am

Many thanks Don, much appreciated.

June 15, 2018 at 5:03 am

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.

June 16, 2018 at 12:08 am

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

June 16, 2018 at 1:02 am

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