Forum Discussion
farism
Sep 11, 2020Copper Contributor
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 e...
- Sep 23, 2020
Use Function instead
place the Business logic in a function and pass the value to it through the code.
arnaudhelin
Sep 14, 2020Copper 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".
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".
- farismSep 15, 2020Copper Contributor
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
- farismalaebSep 23, 2020Iron Contributor
Use Function instead
place the Business logic in a function and pass the value to it through the code.