Limiting initial Foreach loop count

Welcome Forums General PowerShell Q&A Limiting initial Foreach loop count

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
2 years, 3 months ago.

  • Author
    Posts
  • #54807

    Participant
    Points: 1
    Rank: Member

    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.

    Thanks,
    Dave

  • #54810

    Participant
    Points: 0
    Rank: Member
    foreach ($user in ($users | Select-Object -First 100) )

    That ought to do it.

    • #54821

      Participant
      Points: 1
      Rank: Member

      Craig, that works too! I like it. Thanks.

  • #54819

    Participant
    Points: 16
    Rank: Member

    You can use index.

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

      Participant
      Points: 1
      Rank: Member

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

The topic ‘Limiting initial Foreach loop count’ is closed to new replies.