在一个名为的文件中考虑此脚本 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
从更新的示例中,最好将函数存储为ScriptBlocks而不是字符串并用于.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
。
如果要从无法将其存储为ScriptBlocks的源中读取函数,则可以使用将字符串转换为ScriptBlocks [scriptblock]::Create()
。
$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])
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句