1

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
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
PollusB
  • 1,726
  • 2
  • 22
  • 31

1 Answers1

2

In PowerShell you don't use brackets when invoking a function nor do you comma seperate the parameters. You instead call Recurse 1 like this:

Recurs1 -obj 'aaa' -level 0

And the whole function:

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

As TessellatingHeckler showed in his deleted answer, you can also pass the parameter by its position, e. g.

Recurs1 'aaa' 0

However, I think your script gets more readable when you explicitly specify the parameter names.

Community
  • 1
  • 1
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172