I'm trying to create a recursive function in PowerShell v4. It will parse an object and a level. The object could be a folder structure or a XML node. My code does not work as expected and I need help. The question is how can I pass a [int]level
and an object to a recursive function?
This code will work as expected:
function Recurs([int]$level)
{
Write-Host $level
if ($level -lt 5) {
Recurs( $level + 1 )
}
}
Recurs(0)
It will generate this output:
0
1
2
3
4
5
But when I add a new parameter, then $level
loose it's capability to remember it's value. I guess it has something to do with ByVal or ByRef but I'm not sure how to resolve it. In this example, the result will return infinite 0:
function Recurs1($obj, [int]$level)
{
Write-Host $level
if ($level -lt 5) {
Recurs1( $level + 1 )
}
}
Recurs1('aaa', 0)
And with this example,
function Recurs2([int]$level, $obj)
{
Write-Host $level
if ($level -lt 5) {
Recurs2( $level + 1 )
}
}
Recurs2(0 ,'aaa')
I get an error:
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