atownson
atownson

Reputation: 368

Powershell with GUI will not set variable

I am learning Powershell and attempting to create a GUI interface like the example here.

However, when I run this as it is, $x is never defined. Any idea what I could be doing wrong? I know it has something to do with:

$OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})

Because if I change it to:

$OKButton.Add_Click({Write-Host "worked";$objForm.Close()})

It does return worked.

Upvotes: 3

Views: 7436

Answers (2)

Alex_P
Alex_P

Reputation: 2952

Instead of $Global:variable one can also use the $Script:variable which will increase the scope of your variable to your script. Hence, if you use A function to create buttons and within the function you also have the .Add_Click({}) function, it will work within your function scope. The $Script: variable increase the scope of the variable to the nearest parent script file scope.

Upvotes: 0

Frode F.
Frode F.

Reputation: 54881

Your actionblock is running in a seperate local scope. To modify a global(session-wide) variable, use a scope-modifier($global:varname). E.g.:

$OKButton.Add_Click({$global:x=$objListBox.SelectedItem;$objForm.Close()})

More about scopes at Technet - about_Scopes (or write Get-Help about_scopes in PowerShell)

Upvotes: 9

Related Questions