Understanding scope of functions in powershell workflow Understanding scope of functions in powershell workflow powershell powershell

Understanding scope of functions in powershell workflow


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 workflow1in func1in workflow2in func2

More about it here


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.


To vaguely summarise all the responses, don't question why it behaves this way, just accept that it does and deal with it. Fair enough.

I've written a whole deployment pipeline in none-workflow Powershell and I'd like to optimise it by using workflow's "foreach -parallel" however it seems the tax on doing so is that I'd have to go back and re-write the whole thing in workflow. That's too big a tax to pay unfortunately just to get a parallel foreach loop.

Lesson learned - use Powershell workflow from the get-go.