Powershell global variable is not inherited by child scripts

孤街浪徒 提交于 2019-12-11 14:55:58

问题


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): 

回答1:


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


来源:https://stackoverflow.com/questions/50843217/powershell-global-variable-is-not-inherited-by-child-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!