Avatar of Kelly Garcia
Kelly Garcia
Flag for United Kingdom of Great Britain and Northern Ireland asked on

PowerShell run commands once in nested foreach

Hi,

I have a code similar to the below:

foreach($a in @(1..3)){
echo $a
foreach ($b in @("a","b","c","d","e")){
echo "Test"

}

}

Open in new window


i want the echo "test" to only happen once within the first foreach.  my real code contains powershell commandlets and i only want to execute these commandlets once per 1..3. so first loop will output 1, then it will go to the next foreach each which gives value a. within a, b, c, d, e. i want to echo test, however when it goes to 2 which is the first foreach, i dont want to echo test anymore. i hope this makes sense.  How can this be achieved?
Powershell

Avatar of undefined
Last Comment
footech

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
footech

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Kelly Garcia

ASKER
I think you've done it, brilliant!!
Kelly Garcia

ASKER
still need to test though
Kelly Garcia

ASKER
can you give me an example of begin process end please.

thank you.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Kelly Garcia

ASKER
apologies I mean begin process end for this scenario
Kelly Garcia

ASKER
should $first be outside of the if statement?
footech

In my example, line 8 could also be moved after the If statement (afer line 9), or after the second foreach loop (after line 10) but still with the first foreach loop.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Kelly Garcia

ASKER
thank you
footech

This scenario doesn't really lend itself well to using begin, process, and end.  But here's an example (didn't include end):
1..3 | ForEach-Object -Begin { echo "test" } -Process {
    echo $_
    foreach ($b in @("a","b","c","d","e")){
        # blah
    }
}

Open in new window