How Can I Exit a For Each Loop?

How Can I Exit a For Each Loop?

  • Comments 15
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! Is there any way to exit a loop in a script?

-- MW

SpacerHey, Scripting Guy! AnswerScript Center

Hey, MW. You know, when we started writing this column we intended it to be a simple little thing that answered those basic questions so many beginning scripters have:

How can I determine the current date in a script? (Use VBScript’s Date function.)

How can I echo messages to the command window instead of in a message box? (Run the script under the CScript scripting host.)

How can I tell whether a variable holds a numeric value? (Use the IsNumeric function.)

Ah, but you know how it goes: soon more and more people were telling us how much they liked the column, and soon we began answering questions that allowed us to show off our scripting skills. Eventually we got so full of ourselves that we no longer answered questions like, “How can I show a dialog box that people can use to enter information?” (use VBScript’s InputBox function) but instead we only answered complicated and esoteric questions, questions like, “How can I write a script that will exorcise the ghost of Greta Garbo?” Interesting and useful, but often-times a bit beyond what the beginning scripter was ready to tackle.

Note. Scoff if you will, but to date none of the Scripting Guys has ever been haunted by the ghost of Greta Garbo.

As you probably all know, after a wild, non-stop night of partying with supermodels you can’t help but wake up the next morning feeling a little remorseful. And the same thing is true here. We know that we’ve been neglecting a good portion of our audience - the beginning scripter -and we’ve vowed to never let that happen again. Because of that, every now and then we’ll be sure the answer one of the more basic scripting questions; promise. And just to prove it, today we’ll tell you how you can exit a For Each loop. (Obviously something people are interested in, because we’ve gotten several questions on this very topic.)

Did you just hear a noise? Sounded like a ghost or something….

OK: exiting a loop. Let’s say you have an NT 4 domain and you want to determine whether a particular user account exists in that domain. If you were running Active Directory this would be a no-brainer: you could just search for that account and have an answer is seconds. But this is NT 4 and no ADO provider exists for NT 4; that means you can’t search the accounts database on an NT 4 domain.

So how can you tell whether or not a user account exists in an NT 4 domain? Well, one way to do this is the good old-fashioned, brute force way: you retrieve all the accounts and check each one. And the easiest way to do that is in a For Each loop:

Set objComputer = GetObject("WinNT://fabrikam,domain")

For Each objItem in objComputer
    If objItem.Name = "kenmyer" Then
        Wscript.Echo "Account found."
    End If
Next

There’s nothing wrong with this approach, and - depending on your needs - you might have no choice but to methodically slog your way through the entire collection of accounts. The only problem is that this can be very slow; on a test domain with about 30,000 accounts it took well over 2 minutes for our script to complete. If the account you’re looking for happens to be the very last account in the collection there’s not much you can do about that. But what if the account you’re looking for happens to be the very first item in the collection? In that case you’re going to immediately find what you’re looking for but then have to wade through 29,999 more accounts just so you can complete the For Each loop.

Well, unless you explicitly exit the loop that is:

Set objComputer = GetObject("WinNT://fabrikam,domain")

For Each objItem in objComputer
    If objItem.Name = "kenmyer" Then
        Wscript.Echo "Account found."
        Exit For
    End If
Next

In our first script we checked each account to see if it had the name kenmyer; it if did we echoed back the message “Account found.” We do the same thing here, but with one difference: after echoing the message we then call the Exit For statement. Exit For immediately takes us out of our loop; if kenmyer happens to be the first account found we’ll never look at any of the other 29,999 accounts. That’s it: call Exit For and you are out of the loop. (We Scripting Guys seem to always be out of the loop, but that’s a different story.)

If you’d like to see the effects of Exit For, run this script, which simply writes the numbers 1 through 1,000 to the screen:

For i = 1 to 1000
    Wscript.Echo i
Next

Now try this script, which calls the Exit For statement if the variable i equals 3:

For i = 1 to 1000
    Wscript.Echo i
    If i = 3 Then
        Exit For
    End If
Next

See the difference? If you can write code like that you’ll never have to worry about the ghost of Greta Garbo ever again.

You sure you didn’t hear that? Sounds like chains rattling….

Exit For works in either a For Each or a For Next loop. But what if you need to exit a Do loop? No problem: just call Exit Do. What if you want to exit a subroutine? Just call Exit Sub. To exit a function call Exit Function. In other words, there’s no reason to ever again find yourself trapped in a never-ending loop; if you want out, just Exit.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • hey scripting guy,

    i was wondering how to stop a loop whit a specific key like this:

    a=inputbox ("Message")

    Set WshShell = WScript.CreateObject ("WScript.Shell")

    do until (backspace)

    WScript.Sleep 5000

    WshShell.SendKeys (a)

    WScript.Sleep 1000

    WshShell.SendKeys "{enter}"

    loop

    but the (backspace) doesn't work

    thanks for replying

  • We have this with no joy.  Must be to use backspace many times to make joy.

    Please try to make backspace more and you will have joy to.

    Also must write in script not other langauge.

  • what do you mean with joy?

    and doesn't need to be backspace, just a 'not often used' key. and how should i write it then in vbscript?

  • For Each element In group

      [statements]

      [Exit For]

      [statements]

    Next [element]

    msdn.microsoft.com/.../tywtbxd0(v=vs.85).aspx

  • a=inputbox ("Message")

    if a = "" Then Exit Do

  • yeah

    ok thanks, but i do

    n't quit undrstands it can yo

    u please do it i

    n this.

    a=inputbox ("Message")

    Set WshShell = WScript.CreateObject ("WScript.Shell")

    do until (backspace)

    WScript.Sleep 5000

    WshShell.SendKeys (a)

    WScript.Sleep 1000

    WshShell.SendKeys "{enter}"

    loop

  • Your column reminded me that so often I find the answer to what I am looking for here, and I just wanted to say a general thank you to both the script guys and Microsoft for letting them do this. It is a great resource and one I am very thankful for.

    Thanks Again for doing what you do!

    Todd

  • Start your New Seasons weight-loss system now with the Venus Aspect and bring in the next season with a hot, attractive human body. https://www.rebelmouse.com/venusfactorreviewslogin/

  • Headline Insurance policy - You may have to take out insurance on your title €"mandatory in some declares. http://www.quickmove.com/sell-my-house-quick.html

  • Perfecting taruhan bola techniques will have a look at them nearer to the resources. Are you also enthusiastic about continually successful in taruhan bola? Below are some suggestions and suggestions for you http://rajabetting.org/ibcbet/

  • If a home is being controlled additional interest to detail in cleaning the outer lining area is important. http://social.thematesrates.com/blogs/64403/105525/chapter-seven-private-individual

  • A research did display that when artificial GH was given to lab creatures it triggered melanoma, and there have been some recommendations that artificial hormone treatment improved melanoma in females. http://www.ber-ded.com/berdedforum/index.php/290282-procedures-to-elevate-human-growth-hormone-by-organic-signifies

  • Security is the foundation of toys and games, only in guaranteeing the protection of toys and games based on the growth of toy function to give the toy psychological value, or else all is the sky. http://www.myrctopia.com/hwca/

  • Hello! I was wondering how I would be able to have my script return to the main menu after it has finished running. Thanks!