Powershell with GUI will not set variable

2019-02-26 01:02发布

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.

1条回答
成全新的幸福
2楼-- · 2019-02-26 01:35

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)

查看更多
登录 后发表回答