Variables persist outside of loops?

Tagged: 

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of JohnRock Bilodeau JohnRock Bilodeau 2 years, 4 months ago.

  • Author
    Posts
  • #17969
    Profile photo of JohnRock Bilodeau
    JohnRock Bilodeau
    Participant

    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

  • #17972
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #17978
    Profile photo of JohnRock Bilodeau
    JohnRock Bilodeau
    Participant

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

  • #17979
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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).

  • #17984
    Profile photo of JohnRock Bilodeau
    JohnRock Bilodeau
    Participant

    That's pretty cool.

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

You must be logged in to reply to this topic.