[英]Using Variable in other scripts/ pulling variables from script
I have multiple Variables in my first Script我的第一个脚本中有多个变量
$var1= Moon
$var2= Sun
$var3= Earth
Some lines with var1, var2, var3...一些带有 var1、var2、var3 的行...
... ...
... ...
In a few other scripts I have lines which need those variables but I do not want to define them in those scripts, only in the first one.在其他一些脚本中,我有需要这些变量的行,但我不想在这些脚本中定义它们,只在第一个脚本中定义它们。
EDIT: Basically I am trying to pull variables from anther script, while only running the pulling script.编辑:基本上我试图从花药脚本中提取变量,同时只运行拉取脚本。
Write-Host"$var1"
Write-Output"$var2"
... ...
... ...
I've found a few answers online, but those did not really help me... hope someone here can:D我在网上找到了一些答案,但这些并没有真正帮助我......希望这里有人可以:D
@Emil Horstmann @埃米尔霍斯特曼
Well to start you can "dotsource(. C:\test\test.ps1)" the first script from the second one meaning that all the variables will be loaded with it.首先,您可以“dotsource(. C:\test\test.ps1)”第二个脚本中的第一个脚本,这意味着所有变量都将被加载。
You can also pass arguments between files:您还可以在文件之间传递 arguments:
# file1.ps1
$var1= Moon
$var2= Sun
$var3= Earth
C:test\test.ps1 $var1 $var2 $var3
############################################################
# file2.ps1
write-output $args[0] # moon
write-output $args[1] # sun
write-output $args[2] # earth
Another option is to write them to a file and pull them out in the new script (xml, json, csv, etc.) Or you make a file3.ps1 wich calls both the scripts while passing variables to them.另一种选择是将它们写入文件并在新脚本中将它们拉出(xml、json、csv 等)或者您制作一个 file3.ps1,在将变量传递给它们的同时调用这两个脚本。
EDIT: After some testing i found that if you call the second file from the first the variable can just be used.编辑:经过一些测试,我发现如果您从第一个文件中调用第二个文件,则可以使用该变量。 Your sample code will work.您的示例代码将起作用。
# File1.ps1
$var1= "Moon"
$var2= "Sun"
$var3= "Earth"
C:\test\test.ps1
# test.ps1
write-host $var1
write-output $var2
write-warning $var3
Your original code would have worked outside of the syntax errors.您的原始代码可以在语法错误之外工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.