SMA runbook workflows and PowerCLI

Has anyone been successful using Service Management Automation (SMA) to call runbook PowerShell workflows that leverage PowerCLI? I for the life of me cannot get them to work reliably, if at all. My setup is as follows… My workflows pull in a stored credential asset along with a param. The credential artifact along with my param are passed to my InlineScript block with $using (e.g. $using:MyCredAsset etc). Also in my InlineScript is a line to load the PowerCLI modules along with a Connect-ViServer to connect to vCenter. This is followed with a simple $vm = Get-VM and a Write-Output $vm. I run my workflow with Start-SMARunbook @params and off goes my runbook to SMA. I get the output as expected, all is good.

workflow Get-VMWorkFlow_example
    $cred = Get-AutomationPSCredential -Name 'cred_vcenter'
    InlineScript {
        Get-Module -ListAvailable VMware* | Import-Module | Out-Null
        Connect-VIServer -Server vcenter -Credential $using:cred | Out-Null
        $vm = Get-VM -Name $using:VMName
        Write-Output $vm

My issue occurs when I run this runbook multiples times within about 10-20 seconds of one another. I get a variety of errors that lead me to believe the PowerCLI established ‘vis’ PSDrive, modules, and established ViServer connections are overlapping with one another. I have tried all sorts of things to detect whether the ‘vis’ PSDrive or $global:DefaultVIServers already exists, and if not, then and only then import the modules and run connect-viserver. Nothing seems to make a difference. If I remove SMA from the equation and use workflows nativity on my workstation I DO NOT have any of the issues \ errors mentioned. This makes me think it’s an issue with SMA calling workflows.

> Import-Module : The specified mount name ‘vis’ is already in use.
> Import-Module : Exception calling “OnImportModule” with “2” argument(s): “Object reference not set to an instance of an object.”
> Get-VM You are not currently connected to any servers. Please connect first using a Connect cmdlet.
> Connect-VIServer : Value does not fall within the expected range.
> Connect-VIServer The server connection ‘ad\MyUser@vcenter:443’ is required by the current operation. The connection does not exist, possibly because it was actively closed or timed out.

Things to note:
> Sometimes the workflows succeed and give the expected output.
> Sometimes the workflows succeed and give the expected output with the errors discussed above.
> Sometimes one or two workflows succeed with expected output while other fail with errors.
> I do not see this behavior with other PowerShell modules that rely on PSDries (e.g. ActiveDirectory).

Thanks for the help,

I think PowerCLI was just not designed to run in that kind of context. As you surmise, it’s probably timing related, and probably connected to the way SMA parallelizes things.