1

I am trying to understand how Receive-Job works internally. In below code I can see where Job object keeps records from different steams:

$InformationPreference = 'SilentlyContinue'

$sb = {
    $VerbosePreference = 'Continue'
    $InformationPreference = 'Continue'
    $WarningPreference = 'Continue'

    Write-Warning 'warning1'
    Write-Information 'information1'
    Write-Warning 'warning2'
    Write-Information 'information2'
    Write-Verbose 'verbose1'
    Write-Information 'information3'
}

$job = Start-Job -ScriptBlock $sb | Wait-Job

# my messages are here:
$job.ChildJobs[0].Verbose.Count     # prints 1
$job.ChildJobs[0].Information.Count # prints 3, only InformationRecord has TimeGenerated property
$job.ChildJobs[0].Warning.Count     # prints 2

Receive-Job $job

# prints:
# WARNING: warning1
# information1
# WARNING: warning2
# information2
# VERBOSE: verbose1
# information3

But how I can write my own version of Receive-Job and keep original order of different messages? I tried to check source code, but it doesn't have a lot of sense:

https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs

private void WriteJobResults(Job job)
{
    // ...

    Collection<PSObject> output = ReadAll<PSObject>(job.Output);
    foreach (PSObject o in output)
    {
        // ... 
        WriteObject(o);
    }

    Collection<ErrorRecord> errorRecords = ReadAll<ErrorRecord>(job.Error);
    foreach (ErrorRecord e in errorRecords)
    {
        // ...
        mshCommandRuntime.WriteError(e, true);
    }

    Collection<VerboseRecord> verboseRecords = ReadAll(job.Verbose);
    foreach (VerboseRecord v in verboseRecords)
    {
        // ...
        mshCommandRuntime.WriteVerbose(v, true);
    }

    // and so on for other streams...
}
Zergatul
  • 1,957
  • 1
  • 18
  • 28
  • You quote wrong part of code. [That](https://github.com/PowerShell/PowerShell/blob/master@{2019-05-19}/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs#L773-L789) is what actually used. Single collection => no problem with relative order. As far as I can see, that collection does not accessible from public surface. – user4003407 May 19 '19 at 17:41

1 Answers1

0

As @PetSerAl noted I quoted wrong code. This is what is actually getting executed:

// extract results and handle them
Collection<PSStreamObject> results = ReadAll<PSStreamObject>(job.Results);

if (_wait)
{
    foreach (var psStreamObject in results)
    {
        psStreamObject.WriteStreamObject(this, job.Results.SourceId);
    }
}
else
{
    foreach (var psStreamObject in results)
    {
        psStreamObject.WriteStreamObject(this);
    }
}

Unfortunately Results is an internal property. I investigated how it works, and below is the code:

$nonPublicInstance = [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance
$JobResultsProperty = $job.GetType().GetProperty('Results', $nonPublicInstance)

$results = $JobResultsProperty.GetValue($job.ChildJobs[0])

$PSStreamObjectValueProperty = [System.Management.Automation.Remoting.Internal.PSStreamObject].GetProperty('Value', $nonPublicInstance)

foreach ($result in $results)
{
    $value = $PSStreamObjectValueProperty.GetValue($result)
    switch ($result.ObjectType)
    {
        'Verbose' {
            Write-Output "Verbose Record: $value"
        }
        'Information' {
            Write-Output "Information Record: $value"
        }
        'WarningRecord' {
            Write-Output "Warning Record: $value"
        }
        'MethodExecutor' {
            Write-Output "MethodExecutor"
        }
    }
}

For some reason ObjectType=Verbose isn't in collection. I assume verbose records gets extracted from MethodExecutor records somehow. Output:

MethodExecutor
Warning Record: warning1
MethodExecutor
Information Record: information1
MethodExecutor
Warning Record: warning2
MethodExecutor
Information Record: information2
MethodExecutor
MethodExecutor
Information Record: information3
MethodExecutor

I find a better way how to get results from job, however it will work only with newly created jobs. Code below adds event handler for DataAdded event on collections:

$job = Start-Job -ScriptBlock $sb

$records = New-Object 'System.Collections.Generic.List[System.String]'

Register-ObjectEvent -InputObject $job.ChildJobs[0].Verbose -EventName 'DataAdded' -Action { $records.Add('verbose: ' + $Sender[$EventArgs.Index]) }.GetNewClosure() | Out-Null
Register-ObjectEvent -InputObject $job.ChildJobs[0].Information -EventName 'DataAdded' -Action { $records.Add('information: ' + $Sender[$EventArgs.Index]) }.GetNewClosure() | Out-Null
Register-ObjectEvent -InputObject $job.ChildJobs[0].Warning -EventName 'DataAdded' -Action { $records.Add('warning: ' + $Sender[$EventArgs.Index]) }.GetNewClosure() | Out-Null

Wait-Job $job | Out-Null

$records | Format-List

Output:

warning: warning1
information: information1
warning: warning2
information: information2
verbose: verbose1
information: information3
Zergatul
  • 1,957
  • 1
  • 18
  • 28