Calling a Function From Another Function in PowerShell

Question:

First time in PowerShell 5 and I’m having trouble calling a function that writes messages to a file from another function. The following is a simplified version of what I’m doing.

Here’s the error it generates:

I’ve tried moving the logMessage function around in the file and even tried Global scope.

In any other language I would be able to call logMessage from any other function. As that’s the purpose of a function.

What’s the “Workflow way” of reusing a block of code?

Do I need to create some logging module that gets loaded into the Workflow?

Answer:

You could move the functions and function call to an InlineScript (PowerShell ScriptBlock) inside the workflow like below.

Would Output:

As @JeffZeitlin mentioned in his answer, workflows are not PowerShell and are much more restrictive. The InlineScript block allows for normal PowerShell code to be interpreted however the scope will be tied to the InlineScript block. For instance, if you define the functions in the script block then attempt to call the func1 function outside of the InlineScript block (but still within the workflow) it will fail because it is out of scope.

The same would happen if you define the two functions either outside of the workflow or inside of the workflow but not in an InlineScript block.

Now for an example of how you can apply this to running a foreach -parallel loop.

Example call to this workflow would look like this

You will notice (and as expected) the output order is random since it was run in parallel.

Source:

Calling a Function From Another Function in PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply