奇怪的 PowerShell 递归行为

Strange PowerShell Recursive Behaviour

我正在尝试在 PowerShell v4 中创建一个递归函数。它将解析一个对象和一个级别。该对象可以是文件夹结构或 XML 节点。我的代码没有按预期工作,我需要帮助。问题是如何将 [int]level 和对象传递给递归函数?


此代码将按预期工作:

function Recurs([int]$level)
{
    Write-Host $level
    if ($level -lt 5)  {
        Recurs( $level + 1 )
    }
}
Recurs(0)

它将生成此输出:

0
1
2
3
4
5

但是当我添加一个新参数时,$level 失去了记住它的值的能力。我猜它与 ByVal 或 ByRef 有关,但我不确定如何解决它。在此示例中,结果将 return infinite 0:

function Recurs1($obj, [int]$level)
{
    Write-Host $level
    if ($level -lt 5)  {
        Recurs1( $level + 1 )
    }
}
Recurs1('aaa', 0)

在这个例子中,

function Recurs2([int]$level, $obj)
{
    Write-Host $level
    if ($level -lt 5)  {
        Recurs2( $level + 1 )
    }
}
Recurs2(0 ,'aaa')

我收到一个错误:

Recurs2 : Cannot process argument transformation on parameter 'level'. Cannot convert the 
"System.Object[]" value of type "System.Object[]" to type "System.Int32".
At line:8 char:8
+ Recurs2(0 ,'aaa')
+        ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Recurs2], ParameterBindingArgumentTransform 
   ationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Recurs2

在 PowerShell 中,您 在调用函数时不使用方括号,也不用逗号分隔参数。您改为这样调用 Recurse 1

Recurs1 -obj 'aaa' -level 0

以及整个函数:

function Recurs1($obj, [int]$level)
{
    Write-Host $level
    if ($level -lt 5)  
    {
        Recurs1 -obj $obj -level ($level + 1)
    }
}
Recurs1 -obj 'aaa' -level 0

TessellatingHeckler 在他删除的答案中所示,您还可以通过其 位置 传递参数,例如。 G。

Recurs1 'aaa' 0

但是,我认为当您明确指定参数名称时,您的脚本可读性更强。