Search code examples
powershellvariablesfile-copying

Dot Sourced Variables VS Global Variables


I have two ways of referencing script variables from a separate script file. Here are two basic examples:

1. Dot Source
Variables.ps1

$Source = "source"  
$Destination = "dest"

Execute.ps1

. .\Variables.ps1  
Copy-Item -Path $Source -Destination $Destination -Force

2. Global Variable
Variables.ps1

$Global:Source = "source"  
$Global:Destination = "dest"

Execute.ps1

.\Variables.ps1  
Copy-Item -Path $Source -Destination $Destination -Force

I have done research but have yet to find a definitive reason as to use one over the other. Are there limitations or cautions I should exercise when using these methods? Any input is greatly appreciated. Thank you for your time.

EDIT:

@mklement0 gave a great answer as to why to use dot-sourcing over global variables. I would love to still keep this discussion open. If there is another point of view, or an explanation as to when using global variables is more beneficial, I would enjoy hearing it and up-voting accordingly. Thank you.


Solution

  • I suggest you use dot-sourcing, without explicit global variables (method 1):

    That way, it requires a deliberate effort to add variables to the current scope. Note that dot-sourcing adds the variables to the current scope, which may or may not be the current session's global scope (child scopes are created by calling scripts (without dot-sourcing) and script blocks with &, for instance).

    By contrast, using global variables (method 2) creates session-global variables irrespective of invocation method, so that even accidental, non-dot-sourced invocations of the script end up altering the global state.