Variables persist outside of loops?

Welcome Forums General PowerShell Q&A Variables persist outside of loops?

This topic contains 4 replies, has 3 voices, and was last updated by

4 years, 7 months ago.

  • Author
  • #17969

    Points: 1
    Rank: Member


    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


  • #17972

    Points: 1,811
    Helping HandTeam Member
    Rank: 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.

  • #17978

    Points: 1
    Rank: Member

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

  • #17979

    Points: 0
    Rank: 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).

  • #17984

    Points: 1
    Rank: Member

    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.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort