0

I'm new with Powershell.

There is something that amazes me the way PS works, especially how it retains the variable.

Example:

[string]$a=""    
$a = "world" 
$b = "Hello $a" 
write-host $b 

$a = "world2" 
write-host $b

The following is what is resulted:

Hello world
Hello world

Why the second write-host does not display "Hello world2"?

1
  • 2
    Actually, this is how most languages work! Commented Oct 24, 2017 at 8:43

2 Answers 2

1

Just because when you write $b = "Hello $a" the value of $a is expended and the new string is Hello world.

Sign up to request clarification or add additional context in comments.

Comments

0

Like said JPBlanc, you variable is rewrited...

You can do this :

$a = "world" 
Set-PSBreakpoint -Variable b -Mode Read -Action { $global:b = "Hello $a" }

write-host $b  

$a = "world2" 
write-host $b

Or simply use a function:

function SayHello($who){
"Hello $who"
}

$a = "world" 
SayHello($a)

$a = "world2" 
SayHello($a)

2 Comments

No, debugging entry point should be kept for debugging not for programming.
Of course I agree with you, but any method deserves to be known. If we start sorting according to this or that criteria, we do not learn anything ... No?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.