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.
This topic is 4 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
skippy
Posts: 1
Last visit: Wed Feb 19, 2020 11:54 am

Setting a variable once in a recursing function

Post by skippy »

Hello.

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

Thanks.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 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.
This topic is 4 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked