powershellvariablesscopepreferences

Powershell: is there a Scope Preference for Variables?


Morning guys, hopefully just a quick one. Is there a Scope Preference for Variables like there is for some other settings ($ErrorActionPreference, etc)? I'm working on a script that has a bunch of functions that call on information created in each other and I'm just looking to avoid writing $Script: or $Global: in front of each variable everytime (I'm being lazy I know)


Solution

  • Is there a Scope Preference for Variables like there is for some other settings ($ErrorActionPreference, etc)?

    No, scoping behavior is part of the language's core runtime semantics and is not configurable.

    I'm working on a script that has a bunch of functions that call on information created in each other and I'm just looking to avoid writing $Script: or $Global: in front of each variable everytime

    You don't need it everytime - you only need the scope modifier when you're writing to a parent scope.

    Resolution of variables for reading will fall back through parent scopes and eventually the global scope, until a matching variable is found:

    # variable defined at script scope, functions defined in here will fall back to resolving this when `$Config` is referenced
    $Config = @{
      'setting' = 'initialValue'
    }
    
    function Update-Config {
      # Scope modifier is only necessary when "writing up" through the scope stack
      $script:Config = @{
        setting = 'updatedValue'
      }
    }
    
    function Do-Stuff {
      $setting = $Config['setting'] # no need to use script: here
    
      Write-Host "About to do something with '$setting'"
    }
    
    Do-Stuff
    Update-Config
    Do-Stuff
    

    Executing the above in a script file will print:

    About to do something with 'initialValue'
    About to do something with 'updatedValue'
    

    Note that for functions bound to a module, the script: scope is shared across the module - writing to $script:Variable in one module function will cause resolution of non-local $Variable to resolve correctly in any other function in the same module

    For more information about scoped variable resolution, consult the about_Scopes help file