maja
maja

Reputation: 799

Function calling function yields "can't be found"

In a powershell script I have the following scructure:

function Process-File {
    Param ( $FileObject )
    ...
}
function Process-Directory {
    Param ( $DirObject )
    ...
    Get-Childitem $DirObject | ForEach-Object -Parallel {
        Process-File -FileObject $_
    }
}
Get-Childitem -Path $Location -directory | ForEach-Object {
    Process-Directory -DirObject $_
}

This yields the error:

The term 'Process-File' is not recognized as a name of a cmdlet, function, script file, or executable program.

What is going on? Why does Process-Directory can be found but Process-File doesn't?

Upvotes: 0

Views: 47

Answers (1)

Dennis
Dennis

Reputation: 1782

It seems that -parallel is actually starting up new jobs. And those would know nothing about the function that you've only defined locally.

Either you have to send the scriptblock with the foreach call as you do with plain -jobs (don't know if that works with foreach) or define the function again in the foreach script block or globally as in a script profile or a powershell module.

The solution below is the "easiest" to write, but also actually defines the "inner" function over and over again.

function Process-Directory {
    Param ( $DirObject )
    ...

    Get-Childitem $DirObject | ForEach-Object -Parallel {
        function Process-File {
            Param ( $FileObject )
            ...
        }# end inner function

        Process-File -FileObject $_
    }
}
Get-Childitem -Path $Location -directory | ForEach-Object {
    Process-Directory -DirObject $_
}

Upvotes: 2

Related Questions