powershell variable

I am learning powershell and I need to know exactly what is happening here in these two different examples:

PS (1) > $x=0
PS (2) > $a = "x is $($x++; $x)"
PS (4) > 1..3 | foreach {$a}
x is 1
x is 1
x is 1


PS (5) > 1..3 | foreach {"x is $($x++; $x)"}
x is 2
x is 3
x is 4

I understand that $x++ is basically saying 0+1.  But what is the $x doing after that and why does the second count up and the first example does not?
Who is Participating?
The_KirschiConnect With a Mentor Commented:
Hi lardo,

yesterday I had a look at a book I bought some time ago in order to try to answer your question. And guess what...

After not so many pages there appeared - almost like magic - exact the identical lines you posted above. ;-)

It was the book Powershell in Action. I guess that is where you have that example from?

I had a deeper look in it and think I found the explanation although I am not sure if I can actually explain it to you:

Obviously the additional $x is needed to create an output for that variable at all. Otherwise as you can see from my own first example you won't get an output of the value of the variable where it only says "x is ".

If you indeed have that book have a look at the example before with the for-statement.  There is also an additional {$x} that does "create" the actual output of the values from 1 to 10.
I cannot tell you exactly what the $x is for but obviously it is required to get the desired result. See what happens if you change this:

PS C:\> $a = "x is $($x++)"
PS C:\> $a
x is
PS C:\> $a = "x is $x++"
PS C:\> $a
x is 2++
PS C:\>

Your second question is not that complicated:

In the first example it does not count up because foreach of the three "rounds" you are just printing the value of $a which is "x is1".

In the second example in each of the three rounds you have the expression x++ in the "foreach" and thus x gets incremented by 1 each round.

Hope this helps

lardoAuthor Commented:
Thanks for the explanationg.  Sometimes it just takes a little bit more explaining and looking at it for me to figure out code!
I do have that book, and that is what I am using and where I got that example.
Thanks for the help, your explanation helped a lot.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.