Forum Discussion

farism's avatar
farism
Copper Contributor
Sep 11, 2020
Solved

How to run Foreach loop twice

HI, 

I wonder if it's possible to run a foreach loop 2 time, for example

 

 

$x=1..5

foreach ($v in $x) {
Write-Host $v
if ($foreach.current -eq $x.Count){
            Write-Host "I reach the end and will change the values"
            $x=100..105
            $foreach.reset()}
              
}
"End of Scripts"

 

 

The Above script will read the value from X which is 1 till 5, and do some logic in the Foreach loop, But what I am stuck in is after all the execution of Foreach finished, I want to re-execute the same logic but with a different value of $X.

Any Idea about this.

Thanks

 

  • farism 

    Use Function instead

    place the Business logic in a function and pass the value to it through the code.

     

3 Replies

  • arnaudhelin's avatar
    arnaudhelin
    Copper Contributor
    Hi, you should first name correctly your variables, and indent your script.

    foreach ($item in $list)
    {
    //your method
    if ($item -eq $list.Count)
    {
    Write-Host "I reach the end and will change the values"
    $list=100..105
    foreach ($item in $list)
    {
    //your method
    }
    }
    }

    This clearly not the best way to do, but it works for two value of $list. In fact, there is two better solutions :

    - encapsulate your method and run it twice directly.
    - trying to do a "recursive method", which is quite complex.

    It depends on your need, but keep in mind that recursive method is not "finger in the nose".
    • farism's avatar
      farism
      Copper Contributor

      arnaudhelin 

      Thanks, 

      Surely I use a better Var names, but here just to make it short and easy.

      anyway, the method you propose will still need to run a 2 foreach, I want to do it using 1 foreach loop

      Thanks

       

      • farismalaeb's avatar
        farismalaeb
        Iron Contributor

        farism 

        Use Function instead

        place the Business logic in a function and pass the value to it through the code.

         

Resources