gpt4 book ai didi

PowerShell 脚本参数作为数组传递

转载 作者:行者123 更新时间:2023-12-04 10:25:35 26 4
gpt4 key购买 nike

编辑:我已将此处的代码更改为一个简单的测试用例,而不是出现此问题的完整实现。

我试图从另一个调用一个 Powershell 脚本,但事情并没有像我期望的那样进行。据我了解,“&”运算符应该将数组扩展为不同的参数。这不会发生在我身上。

caller.ps1

$scriptfile = ".\callee.ps1"
$scriptargs = @(
"a",
"b",
"c"
)

& $scriptfile $scriptargs

callee.ps1
Param (
[string]$one,
[string]$two,
[string]$three
)

"Parameter one: $one"
"Parameter two: $two"
"Parameter three: $three"

运行 .\caller.ps1导致以下输出:
Parameter one:   a b c
Parameter two:
Parameter three:

我认为我遇到的问题是 $scriptargs数组不展开,而是作为参数传递。我正在使用 PowerShell 2。

如何让 caller.ps1 使用参数数组运行 callee.ps1?

最佳答案

调用 native 命令时,调用类似 & $program $programargs将正确转义参数数组,以便可执行文件正确解析它。但是,对于 PowerShell cmdlet、脚本或函数,没有需要序列化/解析往返的外部编程,因此数组按原样作为单个值传递。

相反,您可以使用 splatting将数组(或哈希表)的元素传递给脚本:

& $scriptfile @scriptargs
@& $scriptfile @scriptargs导致 $scriptargs 中的值应用于脚本的参数。

关于PowerShell 脚本参数作为数组传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19573844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com