I have a script that calls itself. I need to have a the script maintain a variable at the level it is at. In other words, as the script "bubbles out" of the recursion, the variable should be what it was when it called it.
It appears that the scoping of the variables does not allow for that nicely. Sample code (contained in a test.ps1):
param ($y)
set-variable -name temp -scope script -value $y
while ($continue -ne "n")
{
$temp = $temp + 1
$output = "Temp=" + $temp + " ::y=" + $y
write-host $output
$continue = read-host "Pause..."
. .\test.ps1 $temp
}
write-host "exiting $temp - $y"
output:
> PS C:\Users\evanroy\Documents\SCripts> .\test.ps1 1
> Temp=2 ::y=1
> Pause...:
> Temp=3 ::y=2
> Pause...:
> Temp=4 ::y=3
> Pause...:
> Temp=5 ::y=4
> Pause...: n
> exiting 5 - 5
> exiting 5 - 5
> exiting 5 - 5
> exiting 5 - 5
> exiting 5 - 5
desired output:
>PS C:\Users\evanroy\Documents\SCripts> .\test.ps1 1
>Temp=2 ::y=1
>Pause...:
>Temp=3 ::y=2
>Pause...:
>Temp=4 ::y=3
>Pause...:
>Temp=5 ::y=4
>Pause...: n
>exiting 5 - 5
>exiting 4 - 5
>exiting 3 - 5
>exiting 2 - 5
>exiting 1 - 5
Notice how the "exiting" first variable would show that value when it was originally called.