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:
- Parent scopes in powershell are inherited by child scopes
- 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):