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:
What am I missing here? Please help.
Example:
$global:ServerUrl="http://myserver.com"
Write-Host "ServerUrl (Main-Script): $global:ServerUrl"
Powershell.exe -File .\Child-Script.ps1
Write-Host "ServerUrl (Child-Script): $global:ServerUrl"
ServerUrl (Main-Script): http://myserver.com
ServerUrl (Child-Script):
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