victorelec14
victorelec14

Reputation: 188

Powershell reference variable value

i try to create a text in a variable that every time I call it takes the current value in the variable "$ name_person".

In the first round you should give:

Hi Victor
Hi Juan
Hi Pedro
Hi Luis

I'm testing with [ref] but it doesn't take it anyway.

Is there any way to do it without functions or without "replace tag"?

Thank you

$name_person = 'victor'

$message = "hi " + $name_person + ':'


$names = @('Juan', 'Pedro', 'Luis')


foreach ($name in $names){

    $name_person = $name
    $message 

}

Response:

hi victor:
hi victor:
hi victor:

Upvotes: 0

Views: 40

Answers (2)

JA Gordo
JA Gordo

Reputation: 1

It is not necesary to create ScriptBlock, just use variable substitution

$names = @('Juan', 'Pedro', 'Luis')
foreach ($name in $names) {"hi $name"}

Upvotes: 0

Robert Dyjas
Robert Dyjas

Reputation: 5227

You can assign ScriptBlock value to $message and invoke it in your loop:

$message =  { "hi $name_person"}
$names = @('Juan', 'Pedro', 'Luis')
foreach ($name in $names){
  $name_person = $name
  & $message 
}

Upvotes: 1

Related Questions