且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将变量(字符串数组)传递给其他PowerShell脚本

更新时间:2022-11-12 15:12:27

发生这种情况的原因是您要在带双引号的字符串中找到数组 $ 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'}"