Search code examples
powershellgoto

Powershell goto statement replacement


I know powershell doesnt have goto statements. I have a requirement as follows:

foreach($x in $xyz)
{
#something works fine
 if($a -eq $b)
 {
  #something works fine
   if($c -eq $d)
   {
    $c | Add-Content "path\text.txt"
   }else
   {
    #Here I need to go to the first if statement, rather than going to foreach loop
   }
 }else
 {
  #nothing
 }
}

Have tried break :---- and functions but both doesnt seems to work in my case. When I use break :----, it notifies an error in the last else. When I try to use function as below:

foreach($x in $xyz)
{
 #something works fine
  function xyz
  {
   if($a -eq $b)
   {
    #something works fine
    if($c -eq $d)
    {
     $c | Add-Content "path\text.txt"
    }else
    {
     xyz
    }
   }else
   {
    #nothing
   }
  }
 }

it is not entering into the function xyz.

Any other suggestions to achieve this.? Any help would be really appreciated.


Solution

  • I think what you want is nested loops:

    foreach ($item in $data) {
    
      while (condition $data) {
        # Do stuff, calculate $state
    
        if (otherCondition($state)) {
          # without label will exit in inner loop only,
          # execution will continue at Point-X.
          break; 
        }
    
        # more stuff
      }
      # Point-X
    }