从 for 循环中调用 Powershell 函数

Call Powershell function from within for loop

我写了 5 个函数:

Function Task_1 {
‪#‎todo‬ 
}

Function Task_2 {
#todo 
}

同样。

现在我想在 for 循环中一个一个地调用这些函数:

for($i=1; $i -le 5; $i++){
Write-Host Executing Task $i;
Task_$i;
}

当我 运行 这样做时,我得到输出和错误:

Executing Task 1

The term 'Task_$i' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

怎么了?请解决!

Task_$i 不是函数名,它只是一个字符串。

您可以先尝试使用 &:

&Task_$i

或者更直白一点:

invoke-expression Task_$i