You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:
myfunction -channel1 -channel2 *>&1 | ForEach-Object {
$entryType = switch ($_.GetType().FullName) {
'System.Management.Automation.ErrorRecord' { 'error'; break }
'System.Management.Automation.WarningRecord' { 'warning'; break }
default { 'information'}
}
write-eventlog @eventlogparams -entrytype $entryType -message $_
}
Redirection *>&1
sends the output from all (*
) streams to (&
) the success stream (1
), so that all output, irrespective of what stream it came from, is sent through the pipeline.
The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.
See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).
To illustrate the technique with a simpler example:
& { Write-Output good; Write-Error bad; Write-Warning problematic } *>&1 | ForEach-Object {
$entryType = switch ($_.GetType().FullName) {
'System.Management.Automation.ErrorRecord' { 'error'; break }
'System.Management.Automation.WarningRecord' { 'warning'; break }
default { 'information'}
}
'[{0}] {1}' -f $entryType, $_
}
The above yields:
[information] good
[error] bad
[warning] problematic
The list of data types output by the various streams:
Stream Type
------ ----
#1 (Success) (whatever input type is provided).
#2 (Error) [System.Management.Automation.ErrorRecord]
#3 (Warning) [System.Management.Automation.WarningRecord]
#4 (Verbose) [System.Management.Automation.VerboseRecord]
#5 (Debug) [System.Management.Automation.DebugRecord]
#6 (Information) [System.Management.Automation.InformationRecord]
The following code was used to produce the above list (except for the first data row):
& {
$VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
$ndx = 2
"Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information" | % {
& $_ ($_ -split '-')[-1] *>&1
++$ndx
} | Select-Object @{n='Stream'; e={"#$ndx ($_)"} }, @{n='Type'; e={"[$($_.GetType().FullName)]"} }
}
source
namedmyapp
on the target system. that is created with theNew-Eventlog
cmdlet and its-Source
parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/… – BuonarrotiWrite-EventLog
arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case). – XuanxunitSource
must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log. – Buonarroti