Author Posts

August 12, 2014 at 7:03 am

Hi,

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

thanks

August 12, 2014 at 8:17 am

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

Ok thanks for the info. I'll check that out

August 12, 2014 at 9:24 am

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

That's pretty cool.

Thanks for the tip. It will definitely come in handy.