Setting a variable once in a recursing function

Ask your PowerShell-related questions, including questions on cmdlet development!
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.
Posts: 1
Joined: Wed Feb 19, 2020 12:45 pm

Setting a variable once in a recursing function

Post by skippy »


I have a script with a function that recurses through folders. One of the things I'm doing in the function is setting a value for the $previous_folder_location at end of the function. Then on the next run-through I access that value at the beginning of the function and work with the previous_location.

I'm somewhat new so I'm unsure on how to set that variable at the beginning since there's no previous folder yet. I could set it to $null but then it would get set to that on every run.

Would appreciate any help from those that are much smarter than me :D


Posts: 14667
Joined: Tue May 22, 2007 9:57 am
Answers: 5
Has voted: 1 time
Been upvoted: 5 times

Re: Setting a variable once in a recursing function

Post by jvierra »

Start by reading about "Advanced Functions" to learn how functions work and what can be done with them.

help about_Functions_Advanced
get-help about_functions*|fl name,synopsis

The answer to your issue is to set the variable in teh "Begin" block of the function and use the function in a pipeline. YOU caould also just pass the variable to the function as a parameter and initialize it outside of your loop.