1
votes

I´m trying to reuse code on my SMA runbooks but everything I try to put inside a function doesn´t seem to work as expected. For example, If I do this it works and returns the username of the credential:

workflow RB_Test
{   
    $credent = Get-AutomationPSCredential -Name "CRED_TESTE"
    $var = $credent.Username
    "result = ${var}"       
}

Output:

enter image description here

But if I turn into this it doesn't work anymore (returns null):

workflow RB_Test
{   
    function FN_Test 
    { 
       $credent = Get-AutomationPSCredential -Name "CRED_TESTE"
       $var = $credent.Username
       "result = ${var}"        
    }
    FN_Test
}   

Output: enter image description here

I've tried different things but without success. The debug/verbose screen don't return anything different. That also doesn't work:

Inlinescript { 
 . FN_Test
}   

My goal would be to put several functions into a separate module and then import it on my runbooks for reusability but this really seems not to work. This is a runbook (powershell workflow) created in the Service Management Automation (SMA).

I've read that there are some restrictions with Powershell workflow compared to pure Powershell but I am not sure if I am hitting one of them: https://blogs.technet.microsoft.com/heyscriptingguy/2013/01/02/powershell-workflows-restrictions/

Thanks

1

1 Answers

0
votes

Here's what I've had to do to get functions to work:

workflow FunctionTest {
    function log {
        param(
            [string]$Message
        )

        Write-Output $Message
        Write-Output "Filename: $Filename"
        Write-Output "using:Filename: $using:Filename"
        Write-Output "workflow:Filename: $workflow:Filename"
        Write-Output "----"
        ## Under what conditions is 'global' used?  Can't be used in a workflow...Hey Scripting Guy!
    }

    workflow DoSomething {
        param(
            [string]$Filename
        )

        log "Starting DoSomething"
    }

    $Filename = "LogFile_2017.csv"

    log "Starting workflow"

    ## Variables need to be passed into workflow from parent-workflow
    DoSomething -Filename $Filename

    log "End workflow"
}

FunctionTest

I found you need to define your functions before using them. The tricky part was discovering that you have to pass your variables into the child-workflow.

The scope of the variables takes some getting used to.