powershellrecursionpowershell-workflow

Using a recursive function beside a workflow


I have a PowerShell script whose purpose is to get a list of files then do some work on each file.

The list of files is generated by a recursive function like this:

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

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

Separate from this function i do a workflow that takes a list of files and do the 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
        }
    }
}

These two parts are then 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 is this happening when the recursive function and the workflow is separate? Is there any way to work around this issue?


Solution

  • I eventually (of course just a few minutes after posting the question) solved this by just 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
    

    This seem to have made the main script to miss that Recurse uses recursion and it works.