Today I have dealt with logging in PowerShell as well as with the different streams and the pipeline. Unfortunately, none of these solutions really met my needs.
My requirements are:
- I need to output information from PowerShell to a file log.
- The file log has a predefined structure. So it's not enough to just redirect all streams to the file.
- I want to use mainly standard PowerShell functions such as Write-Error, Write-Warning, Write-Verbose.
- The overhead in the code through logging should be minimal.
I have developed the following idea now:
- When calling a function from my script, all streams are piped to a logging function.
- This function separates the debug, verbose, warning and error objects from the resulting object.
- The resulting object is released back into the pipeline.
Here is my solution:
function Split-Streams {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline)]
$InputStream
)
process{
switch($InputStream.GetType())
{
'System.Management.Automation.DebugRecord' {
# Do whatever you want, like formatting an writing to a file.
Write-Host $InputStream -ForegroundColor Gray
}
'System.Management.Automation.ErrorRecord' {
Write-Host $InputStream -ForegroundColor Red
Write-Host ('Error function: {0}' -f $InputStream[0].InvocationInfo.MyCommand.Name) -ForegroundColor Red
}
'System.Management.Automation.VerboseRecord' { Write-Host $InputStream -ForegroundColor Cyan }
'System.Management.Automation.WarningRecord' { Write-Host $InputStream -ForegroundColor Yellow }
default { return $InputStream }
}
}
}
function Write-Messages
{
[CmdletBinding()]
param()
Write-Debug "Debug message"
Write-Output "Output message"
Write-Verbose "Verbose message"
Write-Warning "Warning message"
Write-Error "Error message"
}
$Test2 = Write-Messages -Verbose -Debug *>&1 | Split-Streams
Write-Host $Test2 -ForegroundColor White
So now my question:
- Is there something wrong with my solution?
- Have I missed any problems?
Write-Host
writes directly to the host screen buffer \$\endgroup\$