我试图了解 Receive-Job 如何在内部工作。在下面的代码中,我可以看到 Job 对象在哪里保存来自不同流的记录:
$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
但是我如何编写自己的 Receive-Job 版本并保持不同消息的原始顺序?我试图检查源代码,但它没有多大意义:
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...
}