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

标签 arrays powershell

在名为 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/

相关文章:

powershell - 通过powershell导入Azure自动化模块

PHP + 格式化数组然后在查询中使用

javascript - 如何使用 jquery 创建我的图像数组?

python - 将元素从for循环Python 3放入新数组中

java - 创建数组对象 Java

azure - 如何使用 powershell Az 模块为 Azure AD 应用程序提供所需权限的访问权限

c# - 如何找出谁修改了 C# 或 Powershell 中的共享目录和文件?

powershell - ForEach-Object -Parallel 如何使用

arrays - Powershell:将 pracl 命令的输出通过管道传输到数组

powershell - "copy con"或 "type con > "在 Powershell 中等效吗?