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...
Variable Scope in a Form
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.
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.
Re: Variable Scope in a Form
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) }
Re: Variable Scope in a Form
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) }
- bcafarofmr
- Posts: 2
- Last visit: Wed Feb 07, 2024 12:18 pm