powershellpowershell-workflow

Understanding scope of functions in powershell workflow


Copy and paste the following into a new Powershell ISE script and hit F5:

workflow workflow1{
    "in workflow1"
    func1
}
function func1 {
    "in func1"
    func2
}
function func2 {
    "in func2"
}
workflow1

the error I get is:

The term 'func2' is not recognized as the name of a cmdlet, function, script file, or operable program

I don't understand this. Why would func1 be in scope but not func2? Any help much appreciated. TIA.


Solution

  • Think of Workflows as short-sighted programming elements.

    A Workflow cannot see beyond what's immediately available in the scope. So nested functions are not working with a single workflow, because it cannot see them.

    The fix is to nest workflows along with nested functions. Such as this:

    workflow workflow1
    {
        function func1 
        {
            "in func1"
            workflow workflow2
            {
                function func2 
                {
                    "in func2"
                }
                func2
            }
            "in workflow2"
            workflow2
        }
        "in workflow1"
        func1
    }
    workflow1
    

    Then it sees the nested functions:

    in workflow1
    in func1
    in workflow2
    in func2
    

    More about it here