PowerShell如何使用$MyInvocation进行递归

PowerShell如何使用$MyInvocation进行递归,powershell,Powershell,我正在尝试使用PowerShell实现一些递归函数。以下是基本功能: function MyRecursiveFunction { param( [parameter(Mandatory=$true,ValueFromPipeline=$true)] $input ) if ($input -is [System.Array] -And $input.Length -eq 1) { $input = $input[0]

我正在尝试使用PowerShell实现一些递归函数。以下是基本功能:

function MyRecursiveFunction {
    param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        $input
    )

    if ($input -is [System.Array] -And $input.Length -eq 1) {
        $input = $input[0]
    }

    if ($input -is [System.Array]) {
        ForEach ($i in $input) {
            $i | ##### HOW DO I USE $MyInvocation HERE TO CALL MyRecursiveFunction??? #####
        }
        return
    }

    # Do something with the single object...
}
$i | MyRecursiveFunction
我已经研究了Invoke表达式和Invoke项,但是没有正确的语法。比如我试过

$i | Invoke-Expression $MyInvocation.MyCommand.Name

如果您知道正确的语法,我猜有一种简单的方法可以做到这一点:-)

只需调用函数:

function MyRecursiveFunction {
    param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        $input
    )

    if ($input -is [System.Array] -And $input.Length -eq 1) {
        $input = $input[0]
    }

    if ($input -is [System.Array]) {
        ForEach ($i in $input) {
            $i | ##### HOW DO I USE $MyInvocation HERE TO CALL MyRecursiveFunction??? #####
        }
        return
    }

    # Do something with the single object...
}
$i | MyRecursiveFunction
要在不知道函数名称的情况下调用它,您应该能够使用$myInvocation.InvocationName调用它:

Invoke-Expression "$i | $($myInvocation.InvocationName)"

这是一个老问题,但由于没有令人满意的答案,我也有同样的问题,以下是我的经验

如果名称更改或函数超出范围,则按名称调用函数将中断。管理起来也不是很好,因为更改函数名需要编辑所有递归调用,而且很可能会打断使用prefix选项导入的模块

#一个简单的递归倒计时函数
函数倒计时{
参数([int]$count)
美元计数
如果($count-gt 0){countdown($count-1)}
}
#还有打破它的方法
$foo=${函数:倒计时}
函数倒计时{“失败”}
&$foo 5
$MyInvocation.InvocationName
稍微好一点,但在上面的示例中仍然会中断(尽管原因不同)


最好的方法似乎是调用函数的scriptblock,
$MyInvocation.MyCommand.scriptblock
。这样,不管函数名/作用域如何,它仍然可以工作

函数倒计时{
参数([int]$count)
美元计数
if($count-gt 0){&$MyInvocation.MyCommand.ScriptBlock($count-1)}
}

我建议用另一个变量名更改
$input
$input
是powershell脚本@CB中的保留和自动填充变量。明白了,谢谢。实际上,我希望用我的变量隐藏自动变量,但现在回想起来,这可能不是一个好主意。这是一个完全有效的解决方案。但是,我要实现的功能不止一个。每次,我剪切并粘贴样板代码来处理作为单个对象在数组中的馈送,我必须记住将一行更改为新的函数名。当我忘记改变它时,这已经给我带来了好几次问题。我不是PS专家,一般来说可能有更好的方法,但现在,我希望使用$MyInvocation使样板更通用。仅供参考,一般来说,如果您重复使用相同的样板代码,您可能会进一步推广您的代码。