gpt4 book ai didi

arrays - 如何在 Powershell 中使用数组调用带有参数的函数?

转载 作者:行者123 更新时间:2023-12-01 17:52:18 30 4
gpt4 key购买 nike

在名为 arrays.ps1 的文件中考虑此脚本

Function CallMe
{
param($arg1, $arg2)
Write-Host "`$arg1 is $arg1"
Write-Host "`$arg2 is $arg2"
}

$args = "a","b"
CallMe $args

输出:

PS C:\Users\Moomin\Documents> .\arrays.ps1
$arg1 is a b
$arg2 is

如果我修改它,那么最后一行是

CallMe $args.Split("")

我得到相同的输出。如何将数组传递给函数并将数组元素拆分为参数?

更新

这更接近我正在做的事情:

Function CallMe
{
param($y, $z)
Write-Host "`$y is $y"
Write-Host "`$z is $z"

}

Function DoSomething
{
param($x)
Write-Host "This function only uses one arg: $x"
}

Function DoSomethingElse
{
Write-Host "This function does not take any arguments"
}


$funcCalls = (
("DoSomething", "c"),
("CallMe", ("a","b")),
("DoSomethingElse", '')
)


foreach ($func in $funcCalls) {
Write-Host "Executing function $($func[0]) with arguments `"$($func[1])`""
& $func[0] $func[1]
}

如果我运行它,这就是输出:

PS C:\Users\Moomin\Documents> .\arrays.ps1
Executing function DoSomething with arguments "c"
This function only uses one arg:
Executing function CallMe with arguments "a b"
$y is a b
$z is
Executing function DoSomethingElse with arguments ""
This function does not take any arguments

最佳答案

您可以使用 @ 'splat' 数组,将每个元素作为参数传递给函数。

$array = @('a', 'b')
CallMe @array

从更新的示例中,最好将函数存储为 ScriptBlock 而不是字符串,并使用 .Invoke() 来执行。

$funcCalls = (
({DoSomething @args}, "c"),
({CallMe @args}, ("a","b")),
({DoSomethingElse @args}, '')
)

foreach ($func in $funcCalls) {
Write-Host "Executing function {$($func[0])} with arguments `"$($func[1])`""
$func[0].Invoke($func[1])
}

请注意,参数数组被传递到自动变量 $args 中,该变量被表示为 @args

编辑:

如果您从无法将函数存储为 ScriptBlock 的源中读取函数,则可以使用 [scriptblock]::Create() 将字符串转换为 ScriptBlock。

$funcCalls = (
('DoSomething @args', "c"),
('CallMe @args', ("a","b")),
('DoSomethingElse @args', '')
)

foreach ($func in $funcCalls) {
Write-Host "Executing function {$($func[0])} with arguments `"$($func[1])`""
$script = [scriptblock]::Create($func[0])
$script.Invoke($func[1])
}

关于arrays - 如何在 Powershell 中使用数组调用带有参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201272/

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