40

I have a PowerShell script that does some checks on all Domain Admins in a number of domains. For each user account a number of checks are preformed. When one of them fails the script should go to the next admin in the list.

I currently have something like this (simplified):

Get-QADGroupMember "Domain Admins" | Select-Object SamAccountName | ForEach-Object {

    #Do something
    if(!ThisCheckIsOK)
    {
        break;
    }

    #Do something else
    if(ThisCheckIsNotOK)
    {
        break;
    }

    ...
}

This stops the whole script. Is there a way to go to the next element?

$foreach.movenext() does not work since $foreach is null.

4
  • Maybe you might get better answers on SO?
    – Smudge
    Dec 7, 2011 at 9:34
  • If it would have been a foreach in C++, then yes. Now I'm using a Powershell cmdlet and it is clearly sysadmin-stuff. Dec 7, 2011 at 9:37
  • I think it falls somewhere in between, but your question is generically Powershell (How to advance to the next element in a Powershell loop), even though the specifics are sys-admin related. Just given that there are ~500 Powershell questions on SF, and nearly 4k on SO there are probably some people more qualified to answer the question over there. That's my opinion anyway =)
    – Smudge
    Dec 7, 2011 at 9:47
  • 1
    *I'm not sure if generically is a word but it sounds good
    – Smudge
    Dec 7, 2011 at 9:47

4 Answers 4

51

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

3
  • 1
    that will work for this specific occasion but may not work well in larger scripts with nested loops. Dec 7, 2011 at 17:24
  • 3
    Just think of the code inside the foreach-object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...) Dec 8, 2011 at 10:31
  • 1
    @KevinColby He's right, it actually does work that way...as I discovered after much frustration when I was trying to "return" out of a function from a Foreach-Object loop.
    – Adi Inbar
    Sep 10, 2013 at 1:57
35

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while
5
  • 6
    Foreach-object is not foreach (and not a statement either), so this just works wrong.
    – Steed
    Apr 8, 2016 at 15:18
  • 25
    This exits the whole ForEach-Object statement for me. Return works (i.e. goes to the next object).
    – aucuparia
    May 3, 2016 at 9:27
  • $foreach.MoveNext() can be used in place of continue
    – Djarid
    Aug 12, 2016 at 13:51
  • 17
    This shouldn't be the accepted answer IMO as it is wrong. As the comment from @aucuparia correctly says, you have to return instead of continue. Not very intutitive but that's how it is.
    – Devolus
    Oct 23, 2017 at 8:42
  • @Devolus Not intuitive, but it makes sense when you consider that .ForEach() takes a script-block as an argument. An analogous situation exists in JavaScript.
    – jpaugh
    Sep 11, 2018 at 21:57
3

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

2
  • 2
    foreach(...) and ForEach-Object are two completely different constructs. foreach works the way you describe. ForEach-Object works as others have described. OP is asking about ForEach-Object. P.S.: Also foreach is an alias for ForEach-Object. Yes this is confusing.
    – Ben Scott
    Feb 21, 2020 at 20:09
  • Furthermore for example, $Var | % { If( $LastExitCode -ge 1 ) { Return; }; "something $_" } you want to use Return to go to the next iteration of the object so % is yet another alias but using Return for those type of loops will make it go to the next iteration and not do something against the iterated variable e.g. $_. Nov 13, 2020 at 19:43
1

The continue statement should do what you have asked. Here is an example to ensure this is what you (or anyone who finds this post in a search) wants to do

$vals = @("one", "two", "three", "four", "five", "six", "seven");


foreach ($val in $vals)
{
    Write-Host "";
    Write-Host "$($val) before";
    
    if ($val -eq "three")
    {
        continue;
    }
    
    Write-Host "$($val) after";

}

one before one after

two before two after

three before

four before four after

five before five after

six before six after

seven before seven after

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.