Kage Kage - 3 months ago 8
PowerShell Question

Powershell Assigning variables and retrieving them

So i have been battling all day with powershell, im trying to make something like i put down here. I declare a Variable in the beginning of the script, then i declare 2 function. One function sets a value to the variable, and the other gets the variable.

When getting the variable I get nothing, its empty.

Does anyone have any idea what im doing wrong (im guessing something little and stupid)

$ImUsedInMultplePlaces = ""

Function LetsChooseSomething
{
Write-Host "1: something"
Write-Host "2: Something else"
$answer = Read-Host "Pick One"

switch($answer)
{
"1" { $ImUsedInMultiplePlaces = "We chose something!"; Write-Host "I put it in there!" }
"2" { $ImUsedInMultiplePlaces = "We chose something else!"; Write-Host "I put it in there!" }
}
}

Function ShowMeMyChoice
{
Write-Host $ImUsedInMultiplePlaces
}

Write-Host "Welcome to this amazing script, im about to make you choose"
Write-Host ""
LetsChooseSomething

Write-Host ""
Write-Host "Great Choice!"
Write-Host ""

ShowMeMyChoice

Answer

It's a question of scope. Replace with these and give it a go.

    "1" { $global:ImUsedInMultiplePlaces = "We chose something!"; Write-Host "I put it in there!"  }
    "2" { $global:ImUsedInMultiplePlaces = "We chose something else!"; Write-Host "I put it in there!"  }
Comments