Search code examples
powershelladministrator

Powershell: break from two or more loops


I have a script which pings Systems until it is terminated. The main code block is a function that has a foreach loop nested into a do until loop.

## Start
function start-skript{
    Write-Output 'Ping läuft...'
    $Repetition_Counter = 0
    #Start loop
    do {
        #Host loop
        foreach($system in $Hosts_Array) {
            #Ping Function
            Ping-Host -HostToPing $system
            #Write-Host 'Sleep for' $Pause 'sekunde'
            Start-Sleep -Seconds $Pause
        } $Repetition_Counter ++
    } until($Repetition_Counter -eq $Repetition -or (stop-script))
}

start-skript

It works finely. However, by invoking the stop-script function, the script can only be stopped, only after the function ping-host has been applied to all the devices in the $Hosts_Array. I wan to be able to stop the script by invoking the stop-script function, even if the funtion Ping-host hasn't applied to all the devices in the $Hosts_Array array . I thought, I could do like below

## Start
function start-skript{
    Write-Output 'Ping läuft...'
    $Repetition_Counter = 0
    #Start loop
    do {
        #Host loop
        foreach($system in $Hosts_Array) {
            #Ping Function
            Ping-Host -HostToPing $system
            #Write-Host 'Sleep for' $Pause 'sekunde'
            **stop-script**  ## I've just added the function here
            Start-Sleep -Seconds $Pause
        } $Repetition_Counter ++
    } until($Repetition_Counter -eq $Repetition -or (stop-script))
}

start-skript

I didn't work out. It just comes out of the foreach loop but then starts again with the foreach loop, bcz the foreach loop is into the do until loop.. Any suggestions??


Solution

  • Use a statement label:

    :outer
    do
    {
      :inner
      foreach($i in 1..10){
        if($i -eq 2){
          continue inner
        }
        if($i -gt 5){
          break outer
        }
    
        $i
      }
    }while($true)
    

    Output will be:

    1
    3
    4
    5
    

    Since we continue'd the inner loop on $i -eq 2 and broke out of the outer loop after $i -eq 5