PowerShell getting logs from Jobs

722 Views Asked by At

I am using a PowerShell module called Logging. I use other Jobs to do some work, but unforunately the logs that I write in them are not received by the command Receive-Job.

function Get-Topic {
    [CmdletBinding(DefaultParameterSetName = "Normal")]
    [OutputType(ParameterSetName = "Normal")]
    [OutputType(ParameterSetName = "AsJob")]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "Normal")]
        [Parameter(Mandatory = $true, ParameterSetName = "AsJob")]
        [string]
        $ResourceGroupName,

        [Parameter(Mandatory = $true, ParameterSetName = "Normal")]
        [Parameter(Mandatory = $true, ParameterSetName = "AsJob")]
        [string]
        $Namespace,

        [Parameter(Mandatory = $true, ParameterSetName = "Normal")]
        [Parameter(Mandatory = $true, ParameterSetName = "AsJob")]
        [string]
        $Topic,

        [Parameter(Mandatory = $true, ParameterSetName = "AsJob")]
        [switch]
        $AsJob
    )

    if ($AsJob) {
        $PSBoundParameters.Remove('AsJob') | Out-Null
        return Start-ThreadJob -ScriptBlock {
            param(
                [string]$myFunction,
                [System.Collections.IDictionary]$argTable,
                [System.Collections.Concurrent.ConcurrentDictionary[string, hashtable]] $loggingTargets
            )

            $loggingTargets.Keys | ForEach-Object { Add-LoggingTarget -Name $_ -Configuration $loggingTargets[$_] }
            $cmd = [scriptblock]::Create($myFunction)

            & $cmd @argTable
        } -ArgumentList $MyInvocation.MyCommand.Definition, $PSBoundParameters, (Get-LoggingTarget)
    }

    $topicObj = Get-AzServiceBusTopic `
        -ResourceGroupName $ResourceGroupName `
        -Namespace $Namespace `
        -Name $Topic
    Write-Log -Message "Received topic $($topicObj.Name)" -Level INFO
    return $topicObj
}

Is there any way to redirect the output to the parent powershell session? I saw that Write-Host works, but the logger with the Console target doesn't. Any workarounds for this?

1

There are 1 best solutions below

2
On BEST ANSWER

The solution is the following:

return Start-ThreadJob -StreamingHost (Get-Host) -ScriptBlock {
            param(
                [string]$myFunction,
                [System.Collections.IDictionary]$argTable,
                [System.Collections.Concurrent.ConcurrentDictionary[string, hashtable]] $loggingTargets
            )

            $loggingTargets.Keys | ForEach-Object { Add-LoggingTarget -Name $_ -Configuration $loggingTargets[$_] }
            $cmd = [scriptblock]::Create($myFunction)

            & $cmd @argTable
        } -ArgumentList $MyInvocation.MyCommand.Definition, $PSBoundParameters, (Get-LoggingTarget)

Thanks god the cmdlet Start-ThreadJob allows for such a functionality, basically the param -StreamingHost solved the deal