The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

soostibi (11) [Avatar] Offline
I have a variable:
[40] PS C:> $x = 1,0,2,3,0,4

I make a switch for 0:
[41] PS C:> switch($x) {0 {"zero"}}

I output the $switch.Current:
[42] PS C:> switch($x) {0 {"zero"; $switch.Current}}

So far it's OK, but what happens if I do this:
[43] PS C:> switch($x) {0 {"zero"; $switch}}

I don't understand that. Why did the switch loop stop?

- Tibor
brucepay (155) [Avatar] Offline
Re: What does $switch exactly do?
$switch is the loop enumerator. It lets you do two things:

1. see the current object being worked on
2. advance the enumerator to the next item.

In your example, when you displayed $switch, the output subsystem displayed all of the elements in the enumeration. So, when you try to loop again in the switch statement, the enumerator is already at the end and the loop stops.

You can use this in the switch loop (or foreach loop) to pair up elements. In the following example, the first and second elements are added, then the third and fourth and finally the fifth and sixth:

PS (MTA) (6) > $x = 1,2,3,4,5,6
PS (MTA) (7) > switch ($x) { default {[void] $switch.Movenext(); $_+$switch.current }}
PS (MTA) (smilie >

tomtrias (1) [Avatar] Offline
Re: What does $switch exactly do?
I know I sound like a broken record (boy, I'm dating myself), but is this documented OUTSIDE of your book anywhere?

Is there a way to get the INDEX of the current object, short of declaring and incrementing a separate variable as a counter?

Why doesn't $foreach work within a pipeline to ForEach-Object?

How can I use Get-Member on $foreach? I get the members of $foreach.Current instead; I'm sure they just look like the members of IEnumerator, but maybe there is extra PowerShell goodness somewhere in there...