Limiting initial Foreach loop count

Tagged: , ,

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of david cunningham david cunningham 8 months, 3 weeks ago.

  • Author
  • #54807
    Profile photo of david cunningham
    david cunningham

    I have a Foreach loop that ultimately returns thousands upon thousands of results. I'm having to tweak the output information to get just what I want in the output/results, so having to rerun it multiple times to test the output format and content. I'd like to keep my existing code, but just return the first 100 results.

    What's the simplest method to run through the loop and either exit out or simply stop the loop at 100? Something that I can easily remove or comment out once I dial in the output. I've been piping the output to the screen or file, stopping it after 5 or so seconds, then reviewing the content... but would like to just have it stop at 100.

    I thought there was a switch (or possibly another command) that would allow me something like...

    foreach ($user{100} in $users)

    ...or something like that, indicating to stop the loop at 100.


  • #54810
    Profile photo of Craig Duff
    Craig Duff
    foreach ($user in ($users | Select-Object -First 100) )

    That ought to do it.

  • #54819
    Profile photo of random commandline
    random commandline

    You can use index.

    foreach ($user in $users[0..99]){Code for each $user}
    • #54820
      Profile photo of david cunningham
      david cunningham

      That's more like what I had in mind... Thanks "random Commandline".

You must be logged in to reply to this topic.