r/PowerShell • • May 24 '18

PowerShell Foreach loops explained for Absolute Beginners

https://winsysblog.com/2018/05/powershell-foreach-loops-explained-for-absolute-beginners.html
161 Upvotes

24 comments sorted by

3

u/senorchaos718 May 24 '18

Eat-Reeses would have been a more delicious better cmdlet.

1

u/[deleted] May 24 '18

Ha. Not an approved verb though šŸ™ƒ

1

u/AutoModerator May 24 '18

Sorry, your submission has been automatically removed.

Accounts must be at least 1 day old, which prevents the sub from filling up with bot spam.

Try posting again tomorrow or message the mods to approve your post.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

16

u/[deleted] May 24 '18

I loved your meaningful code. It really makes me mad when "beginner examples" use foobar, abc, def, etc. The Reese's lingo was perfect. It made it more clear than ever.

8

u/BlackV May 24 '18

should have gone into difference between foreach and foreach-object

0

u/[deleted] May 24 '18

[deleted]

9

u/BlackV May 24 '18 edited May 24 '18

they behave differently,

foreach ($example in $examples) {code $example}    

evaluates the entire collection of $examples then runs your code.

foreach-object {code $_}    

works on each $_ as it comes down the pipeline.
edit: apparently underscore causes italics? i thought that was the asterix

0

u/[deleted] May 24 '18

[deleted]

8

u/Lee_Dailey [grin] May 24 '18

howdy singularity098,

they are entirely different things with a very unfortunate short name for ForEach-Object = ForEach.

the foreach ($Thing in $Collection){} is a loop construct.

the ForEach-Object and its unfortuante short name are pipeline constructs to carry out a process on each item in the pipeline as it arrives & then send whatever the result is on to the next step in the pipeline.

very, very, very different things ... [grin]

take care,
lee

3

u/BlackV May 24 '18

well here's a nice explanation (and another reason alias are not something I like)

foreach is an alias of ForEach-Object but it appears to also be a keyword (which is confusing).

The foreach ($<item> in $<collection>){<statement list>} syntax you are using is help about_foreach.

The foreach as ForEach-Object alias is help ForEach-Object.

The keyword foreach operates over each $<item> in the $<collection> as given in the () bit.

The alias foreach/function ForEach-Object operates over each item of the collection it receives as input.

2

u/Ta11ow May 25 '18

So basically there are two 'foreach' things in PS.

Type one is a language feature in the same way switch is - it's not a cmdlet at all:

foreach ($item in $collection) {$item}

This type will use more RAM at crunch time, but operates much quicker. It does however have to wait for the entire collection to be neatly packaged before it can begin.

Tye 2 is a cmdlet alias for ForEach-Object.

$collection | foreach {$_}

Basically if you use the word 'foreach' in a pipeline, PS assumes you mean ForEach-Object, because that is the alias for it, and although the language feature takes priority if it is valid in the present context, it is part of PS's expression syntax, none of which is valid in a pipeline except as the initial input.

The cmdlet, being a pipeline based construct, operates differently. It will start processing as soon as the first object turns up at the door, because the pipeline only wraps collections into arrays at the very end; while it's processing, it operates on individual objects and just keeps passing the baton.

As a result, using the cmdlet form tends to use less RAM at any one point in time. However, because it lacks the advantages of an array type collection (fast access to members) and can only process things as it receives them (if an earlier cmdlet is holding things up a bit, it just sits there and waits for its next input) it tends to end up being slower overall, although this is somewhat alleviated in some circumstances by the fact that it doesn't have to wait for a complete collection before starting work. There are probably some circumstances where the cmdlet may overall perform better, but it's not a clear winner by any means.

I really do wish they'd do away with the foreach arias and make a clear distinction between the two, because they do operate very differently.

2

u/BlackV May 24 '18 edited May 24 '18

and sorry yes I realise its an alias it's how I remember the difference in what I'm using it for
Edit, apparently it isnt :)

4

u/eerilyweird May 24 '18

I guess I don’t get how command line works. Can you write multiple lines of code like this in a command line? Isn’t the nature of a command line that you write one line of something and hit enter? Stupid question, I’m sure.

3

u/ka-splam May 24 '18

Can you write multiple lines of code like this in a command line?

Yes, press shift+enter. Multiline command line.

4

u/SSChicken May 25 '18

Yep but in this situation you wouldn’t even need to. Since there’s an open bracket { after the foreach statement, the command(s) won’t execute until that is closed }

2

u/AkuSokuZan2009 May 25 '18

To expound on what has already been said in response, there is also powershell ise which is basically a powershell prompt with a scripting pane on top that is notepad++ like. You can run the entire command set from the script pane, run a selected section, or type out the command directly in the prompt. Useful for writing longer more complex scripts.

1

u/Lee_Dailey [grin] May 24 '18

howdy eerilyweird,

PoSh is both a command line tool AND a full-on scripting lingo. so you can do either - or both. [grin]

you can take almost any script and replace the newline chars with ; chars and run it as "one line with an enter at the end" if you really wanna. NOT recommended, but it is possible ...

take care,
lee

2

u/eerilyweird May 25 '18

Interesting, thanks! I think I knew you could jumble it all on one line and had heard of this as a silly thing to do, but didn’t know there was another option for longer scripts. I had thought longer scripts just ā€œweren’t for command lineā€ and should be done in some other language or what not. Seems I had that wrong.

1

u/Lee_Dailey [grin] May 25 '18

howdy eerilyweird,

you are welcome! glad to help a tad ... that misconception is fairly common. [grin]

if you want to see some of what can be done, take a look at the top & gilded tabs of this and the /r/usefulscripts subreddits some time.

take care,
lee

3

u/1RedOne May 24 '18

Hey Dan, nice explanation!

Question about your WordPress theme, how did you add the cool 'Follow me on Twitter' button to the bottom of your post?

2

u/SeriousMemes May 24 '18

This is excellent, I've used these loops in the past from examples I have found but this helps clarify how they really work thank you so much for explaining it to me like I'm a child haha.

I would love to read more articles like this

2

u/sambooka May 24 '18

Nice.. I used to be great with for /f loops in CMD and I get that PS is much more powerful (see what I did there?) but it taking a while to get it under my thumb.

Thanks for posting!