1

I have a Windows PowerShell 3.0 script with a workflow and 2 simple functions. Without the workflow I can use my Log function inside my DoSomething function but with the workflow I cannot. The script is:

function DoSomething()
{
    # This is NOT logged
    Log("This will fail...")
}

function global:Log([string]$Message)
{
    Add-Content -Path "C:\my.log" -Value $Message
}

workflow New-CustomWorkflow
{
    try
    {
        # This is logged
        Log("Starting with the workflow")
        DoSomething
    }
    catch
    {
        # This is logged
        Log($_)
    }
}

New-CustomWorkflow

The content of my.log looks like this:

Starting with the workflow
System.Management.Automation.RemoteException: The term 'Log' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. at Microsoft.PowerShell.Activities.PSActivity.OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, Object value) at System.Activities.Runtime.BookmarkCallbackWrapper.Invoke(NativeActivityContext context, Bookmark bookmark, Object value) at System.Activities.Runtime.BookmarkWorkItem.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)

Is this possible? What am I doing wrong?

JustRonald
  • 103
  • 3
  • 10
  • Possible duplicate of [Understanding scope of functions in powershell workflow](http://stackoverflow.com/questions/27360145/understanding-scope-of-functions-in-powershell-workflow) – stijn May 17 '16 at 11:57

1 Answers1

1

In a workflow, most of what you're invoking is a workflow activity including things like try/catch and what appear to be PowerShell commands. To see what is happening behind the scenes, try this:

(Get-Command New-CustomWorkflow).XamlDefinition

Now wait for your head to explode. :-)

BTW you can have nested functions and workflows. This works for me:

workflow New-CustomWorkflow
{
    function DoSomething()
    {
        workflow Log([string]$Message)
        {
            Add-Content -Path "$home\my.log" -Value $Message
        }

        # This is NOT logged
        Write-Output -InputObject "In DoSomething"
        Log -Message "This will fail..."
    }

    try
    {
        # This is logged
        Write-Output -InputObject "Before inline"
        Log -Message "Starting with the workflow"
        Write-Output -InputObject "After inline"
        DoSomething
    }
    catch
    {
        # This is logged
        Write-Output -Input "Doh $_"
        Log -Message $_
    }
}

New-CustomWorkflow
Keith Hill
  • 194,368
  • 42
  • 353
  • 369