I’m writing some code to figure out how to segment a list of values into more manageable chunks. the reason I want to do this is because I’ll have about 100,000 live values and I want to minimise the failure risk.
$wholeList = 1..100
$nextStartingPoint
$workingList
function Get-NextTenItems()
{
$workingList = (1+$nextStartingPoint)..(10+$nextStartingPoint)
$nextStartingPoint += 10
Write-Host "inside Get-NextTenItems"
write-host "Next StartingPoint: $nextStartingPoint"
$workingList
Write-Host "exiting Get-NextTenItems"
}
function Write-ListItems()
{
foreach ($li in $workingList)
{
Write-Host $li
}
}
Get-NextTenItems
Write-ListItems
Get-NextTenItems
Write-ListItems
I ran the code in the PowerGUI debugger and I’ve noticed my $nextStartingPoint is resetting to 0 when I exit the Get-NextTenItems function.
Why is this happening and how can I prevent it?
Should I also assume that the same thing is happening to $workingList?
In your example
Get-NextTenItemschanges its local variables. There are several ways to resolve this issue, here are two of them:1) Specify the variable scopes explicitly (use prefix
scriptorglobal). Namely, use that variables as$script:nextStartingPoint,$script:workingListinside the function.2) Change the scope of the function on its call. Namely, call the function using the dot operator (“dot-source” the function), i.e. execute it in the current scope. This code works as expected (no other changes needed):
See also