Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 718
serverstackqns Avatar asked Dec 01 '25 00:12

serverstackqns


1 Answers

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
}
like image 60
Richard Avatar answered Dec 03 '25 17:12

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!