Using a recursive function next to a workflow

I have a PowerShell script, the purpose of which is to get a list of files, and then some work on each file.

The file list is generated by the recursive function as follows:

function Recurse($path)
{
    .. create $folder

    foreach ($i in $folder.files) { 
        $i
    }
    foreach ($i in $folder.subfolders) {
        Recurse($i.path)
    }
}

      

Apart from this function, I do a workflow that takes a list of files and does work (in parallel) on each file. The code looks something like this:

workflow Do-Work {
    param(
        [parameter(mandatory)][object[]]$list
    )
    foreach -parallel ($f in $list) {
        inlinescript {
            .. do work on $Using:f
        }
    }
}

      

Then these two parts are combined with the following logic:

$myList = Recurse($myPath)
Do-Work -list $myList

      

The problem is that this generates an error:

A workflow cannot use recursion.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : RecursiveWorkflowNotSupported

      

Why does this happen when the recursive function and workflow are separate from each other? Is there a way to get around this problem?

+3


source to share


2 answers


In the end (of course, just a few minutes after posting the question) solved it by simply extracting the function into its own module:

Get-files.psm1:

function Recurse()
{
    params(
        [parameter(mandatory)][string]$path
    )
    .. create $folder

    foreach ($i in $folder.files) { 
        $i
    }
    foreach ($i in $folder.subfolders) {
        Recurse($i.path)
    }
}

Export-ModuleMember -Function Recurse

      

Get-files.psd1:



@{
...
FunctionsToExport = @(Recurse)
...
}

      

script.ps1:

workflow do-work {
    params(
        [parameter(mandatory)][object[]]$files
    )
    ...
}
Import-Module -Name "path\to\module\get-files.psm1"
$files = Recurse -path $myPath

do-work -files $files

      

It looks like the main script missed that Recurse uses recursion and works.

0


source


Recursive call is not allowed in workflows.

Give your path directly:

Instead of this:

Recurse($myPath)

      



do the following:

Recurse $myPath

      

You can refer to this article:

Adding nested functions and nested workflows

+1


source







All Articles