Azure / azure-functions-powershell-worker

PowerShell language worker for Azure Functions.
MIT License
206 stars 53 forks source link

PSJobs - Unable to receive jobs #181

Closed ljtill closed 5 years ago

ljtill commented 5 years ago

In the process of building several prototype PowerShell functions and as part of the execution I'm looking to utilize PSJobs. I've hit a error which I'm trying to remediate and determine if it's an issue with my code syntax or the worker. Testing the process flow outside of the function host doesn't seem to throw any errors and returns the expected behavior.

Operating System: macOS 10.14.4 PowerShell Version: 6.2.0 Azure Functions Core Tools: 2.5.553 Function Runtime Version: 2.0.12382.0

$resourceGroups = @()
$subscriptions | ForEach-Object {
    $subscriptionId = $_.Id
    Start-Job -ScriptBlock {
        param (
            $context,
            $subscriptionId
        )
        begin {
            Set-AzContext -Subscription $subscriptionId -AzContext $context
        }
        process {
            $resourceGroups = Get-AzResourceGroup -AzContext $context
        }
        end {
            return $resourceGroups
        }
    } -ArgumentList ((Get-AzContext), $subscriptionId) | Out-Null
}

while (Get-Job -State "Running") {
    Get-Job | Out-Null
    Start-Sleep -Seconds 1
}

Get-Job | ForEach-Object {
    $resourceGroups += Receive-Job -Job $_ -AutoRemoveJob -Wait | Select-Object -ExcludeProperty PSComputerName, PSShowComputerName, RunspaceId
}

When the Receive-Job cmdlet executes I receive the following error in the Console (debug).

[4/2/19 12:59:12 AM] ERROR: An error occurred while starting the background process. Error reported: No such file or directory.
[4/2/19 12:59:12 AM] Result: ERROR: An error occurred while starting the background process. Error reported: No such file or directory.
[4/2/19 12:59:12 AM] Exception: An error occurred while starting the background process. Error reported: No such file or directory.
[4/2/19 12:59:12 AM] Stack: .

Any help / advice would be greatly appreciated!

daxian-dbw commented 5 years ago

Start-Job doesn't work in the application-hosting-powershell scenario by design. This is because the out-of-process background job requires pwsh to be available under $PSHOME. For an application that hosts PowerShell, it's using the NuGet packages and won't have pwsh shipped with it. You can use Start-ThreadJob from the ThreadJob module. PowerShell Function worker has that module in module path by default.

We updated the error message to make it less confusing. Please see https://github.com/PowerShell/PowerShell/pull/9128

ljtill commented 5 years ago

Thanks @daxian-dbw appreciate the quick response!