Keep inner script variables in an outer scope (dotsource)

If you would to access script variables, created while executing the script, from an outer scope, for example a powershell console session, you need to invoke the script with an additional dot and whitespace before its path:

powershell> . .\MyScript.ps1

Technically it just invoke the script content in this scope exactly  (without pushing a new scope to a call stack).

Such invocation will preserve all variables created in the inner scope. You can verify this simply listing all available variables at the scope:

powershell> Get-ChildItem variable:

This approach is useful when you are debugging the script. Or for example, you do not want to change the target script (e.g. adding global: definitions) but are still willing to access its inner state (in variable terms).

If you use a dynamic script name stored in a variable apply a syntax below

powershell> $scriptPath = ".\MyScript.ps1"
powershell> . $scriptPath
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s