Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 921
jamiet Avatar asked Dec 08 '14 14:12

jamiet


2 Answers

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

like image 175
Micky Balladelli Avatar answered Oct 21 '22 10:10

Micky Balladelli


Not really an answer to your question, but more a track to follow. Putting this in a comment would be too long.

From here :

When you run a script workflow, Windows PowerShell parses the script into an abstract syntax tree (AST). The presence of the “workflow” keyword causes the script-to-workflow compiler to use this AST to generate XAML, the format required by the Windows Workflow Foundation runtime. To create the user experience for interacting with this workflow, we then create a wrapper function that has the same parameters – but instead coordinates execution of the workflow within the PowerShell Workflow executive. You can see both the wrapper function and the generated XAML by executing:

Get-Command workflow1 |Format-List *

I did that for your specific workflow (see the workflow1 in the command above) and both XAML and PowerShell generated code are ... interesting. XAML code doesn't include any reference to func2, but contains a reference to func1.

like image 39
David Brabant Avatar answered Oct 21 '22 12:10

David Brabant