PowerShell 从作业中获取日志

PowerShell getting logs from Jobs

我正在使用名为 Logging 的 PowerShell 模块。我使用其他作业做一些工作,但不幸的是,我在其中写入的日志没有被命令 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
}

有没有办法将输出重定向到父 powershell 会话?我看到 Write-Host 有效,但带有 Console 目标的记录器没有。有什么解决方法吗?

解决方法如下:

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)

感谢上帝,cmdlet Start-ThreadJob 允许这样的功能,基本上参数 -StreamingHost 解决了这个问题