如何将变量(字符串数组)传递给其他PowerShell脚本 [英] How to pass a variable (array of strings) to other PowerShell scripts
问题描述
我在一个包含字符串数组的PowerShell脚本中有一个变量$ Tasks,我需要将该变量传递给其他PowerShell脚本并对其进行处理,例如遍历数组并对每个数组进行处理
I have a variable, $Tasks, in a PowerShell script that contains an array of strings, and I need to pass the variable along to other PowerShell scripts and do stuff with it, like loop through the array and do things with each item (string).
但是,在将变量从数组转换为字符串的过程中(通常在命中script2.ps1时),无法遍历它。我需要怎么做才能在整个过程中将变量保持为数组?
However, at some point along the way my variable gets converted from an array to a string (usually when it hits script2.ps1), and I'm not able to loop through it. What do I need to do to keep the variable as an array throughout the entire process?
这是变量的工作流程:
Script1.ps1 :
$Tasks = @(
"Task1 - Name1",
"Task2 - Name2",
"Task3 - Name3"
)
powershell "& {. $pwd\Script2.ps1 -BuildNum $BuildNum; Run-Validation -Tasks $Tasks}"
Script2.ps1 :
param(
$Tasks=$()
)
Function Run-Validation
{
param($Tasks)
If ($Tasks)
{
Test-Tasks $Tasks
}
}
Script3.ps1 :
Function Test-Tasks ($Tasks)
{
ForEach ($Task in $Tasks)
{
do_stuff
}
}
推荐答案
发生这种情况的原因是您要在带双引号的字符串中找到数组 $ Tasks
。在将命令行传递到PowerShell.exe之前,它会扩展为:
The reason this is happening is that you're expanding an array, $Tasks
, inside a double-quoted string. Before your command line is passed to PowerShell.exe, it is expanded to:
Arg 0 is <& {. C:\Script2.ps1 -BuildNum ; Run-Validation -Tasks Task1 - Name1 Task2 - Name2 Task3 - Name3}>
因此 Run-Validation -Tasks
参数只看到 Task1。如果要在Run-Validation函数中查看$ args,则会看到其余的参数。
So the Run-Validation -Tasks
parameter only sees "Task1". If you were to look at $args inside of the Run-Validation function you would see the rest of the arguments.
BTW,为什么要调用另一个Powershell.exe会话?为什么不这样调用:
BTW, why invoke another Powershell.exe session? Why not just invoke like so:
. $PSScriptRoot\Script2.ps1 -BuildNum $BuildNum
Run-Validation -Tasks $Tasks
请注意,如果您在Script2.ps1中取消了脚本级别$ Tasks参数,则以上内容仅在 下起作用。如果不是,则在点源Script2.ps1以访问运行验证功能时,Script2.ps1中的$ Tasks有效地覆盖了Script1.ps1中设置的值。
Note that the above only works if you eliminate the script level $Tasks parameter in Script2.ps1. If not, when you dot source Script2.ps1 to gain access to the Run-Validation function, the $Tasks in Script2.ps1 effectively overwrites the value set in Script1.ps1.
如果您真的想在单独的PowerShell会话中调用它,则可以执行以下操作:
If you really want to invoke this in a separate PowerShell session you can do this:
$OFS="','"
powershell "& {. $pwd\Script2.ps1 -BuildNum $BuildNum; Run-Validation -Tasks '$Tasks'}"
这篇关于如何将变量(字符串数组)传递给其他PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!