从另一个 powershell 脚本加载变量 [英] Load variables from another powershell script
问题描述
我有几个脚本可以重用变量,所以我想在他们自己的 Variables.ps1 脚本中隔离变量,即
$var1 = "1"$var2 = "2"
我正在尝试加载这些变量,然后像这样在 Main.ps1 脚本中打印出来:
.\Variables.ps1$var1$var2
这在我第一次运行 .\Variables.ps1 时有效,但如果我只运行 Main.ps1 则无效.我的环境是 PowerShell ISE.我做错了什么?
Variables.ps1
中声明的变量位于脚本范围".也就是说,您无法在声明它们的脚本范围之外看到它们.将 Variables.ps1
中的变量带入 main.ps1
范围的一种方法是点源" Variables.ps1
.这实际上在 main.ps1
的范围内运行 Variables.ps1
.为此,只需在调用脚本之前添加句点和空格即可:
I have several scripts that could be reusing variables so I'd like to isolate variables in their own Variables.ps1 script, i.e.
$var1 = "1"
$var2 = "2"
I'm trying to load these variables then print them out in the Main.ps1 script like this:
.\Variables.ps1
$var1
$var2
This works if I first run .\Variables.ps1 but not if I just run Main.ps1. My environment is PowerShell ISE. What am I doing wrong?
The variables declared in Variables.ps1
are at "Script Scope". 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
. This, in effect, runs Variables.ps1
at the scope of main.ps1
. To do this, just stick a period and space before your invocation of the script:
. .\Variables.ps1
$var1
$var2
这篇关于从另一个 powershell 脚本加载变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!