none
Back to Basics RRS feed

  • Question

  • So a colleague asked a good question and it relates to something I commonly see in scripts, but can't really answer "why".

    In powershell scripts, where I'm (foreach) looping through a series of file reads, I tend to precede the foreach statement with a $count =2 and after the foreach, close with a $count++

    I can't really say I'm using that particular $count because I know *why*, just that it seems to be very common when iterating through a foreach loop, and frankly it works.

    Searching for documentation on this I'm able to find information about "-count", but that appears to be a different thing entirely.

    If you can point me to some basic information that explains this, I appreciate it.  Thanks very much!

    Friday, March 6, 2015 7:34 PM

Answers

  • $count is just the name of a variable.

    If you iterate a collection with foreach, then you don't need to increment a counter, unless you have a reason for counting the iterations (for example, if you want to know how many iterations completed).


    -- Bill Stewart [Bill_Stewart]

    Friday, March 6, 2015 7:56 PM
    Moderator

All replies

  • It would help to post a short example. From you description I see no purpose for $count.

    Richard Mueller - MVP Directory Services

    Friday, March 6, 2015 7:52 PM
    Moderator
  • $count is just the name of a variable.

    If you iterate a collection with foreach, then you don't need to increment a counter, unless you have a reason for counting the iterations (for example, if you want to know how many iterations completed).


    -- Bill Stewart [Bill_Stewart]

    Friday, March 6, 2015 7:56 PM
    Moderator
  • In PowerShell we do it this way;

    $x=dir c:\
    for($i=0;$i -lt $x.Count;$i++){
        $x[$i].Name
    }
    

    But "foreach" is usually what we want.


    ¯\_(ツ)_/¯

    Friday, March 6, 2015 8:23 PM