[英]Load variables from another powershell script
I have several scripts that could be reusing variables so I'd like to isolate variables in their own Variables.ps1 script, ie 我有几个脚本可以重用变量,所以我想在他们自己的Variables.ps1脚本中隔离变量,即
$var1 = "1"
$var2 = "2"
I'm trying to load these variables then print them out in the Main.ps1 script like this: 我正在尝试加载这些变量,然后在Main.ps1脚本中将它们打印出来,如下所示:
.\Variables.ps1
$var1
$var2
This works if I first run .\\Variables.ps1 but not if I just run Main.ps1. 如果我第一次运行,这是有效的。\\ Variables.ps1但是如果我只运行Main.ps1则不行。 My environment is PowerShell ISE.
我的环境是PowerShell ISE。 What am I doing wrong?
我究竟做错了什么?
The variables declared in Variables.ps1
are at "Script Scope". 在
Variables.ps1
中声明的Variables.ps1
位于“脚本范围”。 That is you can not see them outside of the scope of the script that declares them. 那就是你不能在声明它们的脚本范围之外看到它们。 One way to bring the variables in
Variables.ps1
to the scope of main.ps1
is to " dot source " Variables.ps1
. 将Variables.ps1中的
Variables.ps1
引入main.ps1
范围的main.ps1
是“ dot source ” Variables.ps1
。 This, in effect, runs Variables.ps1
at the scope of main.ps1
. 实际上,这在
main.ps1
的范围内运行Variables.ps1
。 To do this, just stick a period and space before your invocation of the script: 要做到这一点,只需在调用脚本之前粘贴句点和空格:
. .\Variables.ps1
$var1
$var2
# var.ps1
$Global:var1 = "1"
$Global:var2 = "2"
This works. 这有效。 Whether it's better or worse than "dot sourcing" probably depends on your specific requirements.
是否比“点源”更好或更差可能取决于您的具体要求。
PS > .\var.ps1
PS > $var1
1
PS > $var2
2
PS >
Just to ensure correctness ... try this... in main.ps1 只是为了确保正确...在main.ps1中尝试这个...
echo "Test"
. .\Variables.ps1
echo $var1
echo $var2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.