Search code examples
powershellscopeglobal-variables

Powershell global variable is not inherited by child scripts


I have a bunch of powershell scripts, broken down to keep things modular. However, all or most of these scripts rely on certain common variables, like the server they talk to, etc. I'm defining these variable in the global scope and accessing them in the scripts using $global:{Variable} syntax.

This works fine in the script which serves as the entry point. However when the main (entry point) script executes a child script using the following syntax, I no longer can read the value of the same global variable. All I get is empty string.

Powershell.exe -File .\Child-Script.ps1

My understanding is:

  1. Parent scopes in powershell are inherited by child scopes
  2. Global scope should be available throughout all scripts getting executes in the current shell context.

What am I missing here? Please help.

Example:

Parent Script (Main-Script.ps1)

$global:ServerUrl="http://myserver.com"
Write-Host "ServerUrl (Main-Script): $global:ServerUrl"
Powershell.exe -File .\Child-Script.ps1

Child-Script (Child-Script.ps1)

Write-Host "ServerUrl (Child-Script): $global:ServerUrl"

Output

ServerUrl (Main-Script): http://myserver.com
ServerUrl (Child-Script): 

Solution

  • When you launch Powershell.exe you are creating a new powershell session with its own global context. So this:

    Powershell.exe -File .\Child-Script.ps1
    

    Will cause the child script to run in a different context. Instead you can 'Dot Source' the child script which will cause it to be executed in the current context:

    . .\Child-Script.ps1