Link to home
Start Free TrialLog in
Avatar of lardo
lardo

asked on

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}
BASIC TYPES AND LITERALS 63
x is 1
x is 1
x is 1

and....

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?
Avatar of Member_2_3654191
Member_2_3654191
Flag of Germany image

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

Daniel
ASKER CERTIFIED SOLUTION
Avatar of Member_2_3654191
Member_2_3654191
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lardo
lardo

ASKER

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.