Kage Kage - 3 months ago 7
PowerShell Question

Powershell Assigning and Retrieving Variables

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

When getting the variable I get nothing - it's empty.

Does anyone have any idea what I'm doing wrong (I'm 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!"  }