Variable Scope in a Form

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 10 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
bcafarofmr
Posts: 2
Last visit: Wed Feb 07, 2024 12:18 pm

Variable Scope in a Form

Post by bcafarofmr »

I'm trying to populate an array and load a listbox with the values of the array. The problem I'm having is when I call my function to load the array, as soon as I step out of the function, my array is empty.

If I run the code as a regular .ps1 script, it works fine (sending the values of the array to the console instead of a listbox). But if I put that same code into a form (.pff), it doesn't work.

I've tried setting the array scope to script: and global: levels, but that doesn't work no matter where I insert it. I've also tried creating a return value within the function, but that doesn't work either.

I'm still new to coding, but I understand the concept of scope. I guess I just don't understand scoping within Powershell Studio Forms.

Here is some sample code...

function OnApplicationLoad {
$script:arrLocalUsers = @()
$return $true
}

function OnApplicationExit {
$script:ExitCode = 0
}

function LOAD-MY-ARRAY {
$userList = ('Joe','Sam','Benny')
foreach ($user in $userList) {
$arrLocalUsers += $user
}
#Write-Host $arrLocalUsers
return $arrLocalUsers
}

LOAD-MY-ARRAY

foreach ($localUser in $arrLocalUsers) {
Load-ListBox $listbox1 $localUser -append
}

Any assistance would be greatly appreciated. Thanks in advance...
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Variable Scope in a Form

Post by jvierra »

How to load an array into a listbox:
PowerShell Code
Double-click the code block to select all.
$FormEvent_Load={
	#TODO: Initialize Form Controls here
    $a=@('tom','dick','harry')
	$listbox1.Items.AddRange($a)
}
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Variable Scope in a Form

Post by jvierra »

Calling a function to load an array:
PowerShell Code
Double-click the code block to select all.
function LOAD-MY-ARRAY {
	$userList = @('Joe','Sam','Benny')
	return $userList
}


$FormEvent_Load={
    $a=LOAD-MY-ARRAY
	$listbox1.Items.AddRange($a)
}
User avatar
bcafarofmr
Posts: 2
Last visit: Wed Feb 07, 2024 12:18 pm

Re: Variable Scope in a Form

Post by bcafarofmr »

That worked perfectly. Thanks!!
This topic is 10 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked