1

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.

1 Answer 1

3

Dot sourcing is not the same as "calling itself". Dot sourcing works as though you had pasted the script into the current one and began executing it immediately.

You might want to call the script with the & operator instead.

You should thoroughly read about_Scopes.

Sign up to request clarification or add additional context in comments.

2 Comments

Or just call the script directly e.g. .\test.ps1.
doh... I was troubleshooting a different part and forgot I had done that. I knew it was something simple I just couldn't see it... thank you,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.