televisi
televisi

Reputation: 11

PowerShell variable value is not retained

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"?

Upvotes: 0

Views: 106

Answers (2)

Esperento57
Esperento57

Reputation: 17462

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)

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72612

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

Upvotes: 1

Related Questions