This topic contains 4 replies, has 3 voices, and was last updated by
August 12, 2014 at 7:03 am #17969
I had a quick question about using variables inside of loops.
I noticed that if create a variable inside a foreach loop that the variable still exists once i am outside of the loop. This seems a bit odd to me because in most of the other languages that i have used, variables created inside a loop only exist inside that loop, this way you can reuse variable names without fear of carrying data over from a variable used in an other loop.
for example. I'm currently writing a script to handle AD user creation, modification, disabling and deletion. for each of these i have a foreach loop that will loop through the list of users that apply to it. Inside the loop i might want to have a variable called $currentUser, but i wouldn't want for it to be possible for a variable assigned to $currentUser in the user creation loop to show up in the user modification or deletion loop.
Hope this makes sense
August 12, 2014 at 8:17 am #17972KeymasterPoints: 1,811Rank: Community Hero
PowerShell doesn't support the detailed scoping you're referring to. Read about_scope in the shell for details, but briefly what you're seeing is the designed behavior. Keep in mind it's a shell, not a formal programming language.
August 12, 2014 at 9:09 am #17978
Ok thanks for the info. I'll check that out
August 12, 2014 at 9:24 am #17979MemberPoints: 0Rank: Member
Bodies to PowerShell keywords (for, foreach, if, switch, etc) execute out in the scope of wherever that keyword is used, as you've discovered. However, ScriptBlocks have their own scope unless they're dot-sourced. If you wanted to force a foreach loop to have its own scope for variable assignment, you could do something like this:
Sigh... forum software is being a bit of a pain due to ampersand characters being treated specially. See attachment instead.
(Alternatively, you could just put the body of the loop into a function and give it a descriptive name. That might be more readable anyway, and functions already have their own script blocks / scopes).
August 12, 2014 at 10:22 am #17984
That's pretty cool.
Thanks for the tip. It will definitely come in handy.
The topic ‘Variables persist outside of loops?’ is closed to new replies.