Is it possible in powershell when running a script to add a date prefix to all log output?
I know that it would be possible to do something like: Write-Host "$(Get-Date -format 'u') my log output"
But I dont want to have to call some function for each time we output a line. Instead I want to modify all output when running any script or command and have the time prefix for every line.
CodePudding user response:
Notes:
The code requires PowerShell 7 .
The date formatting can be changed through parameters
-DateFormat(see formatting specifiers) and-DateStyle(ANSI escape sequence for coloring).Script-terminating errors such as created by throwing an exception or using
Write-Error -EA Stop, are not logged by default. Instead they bubble up from the scriptblock as usual. You can pass parameter-CatchExceptionsto catch exceptions and log them like regular non-terminating errors. Pass-ExceptionStackTraceto also log the script stacktrace, which is very useful for debugging.Scripted cmdlets such as this one don't set the automatic
$?variable and also don't add errors to the automatic$Errorvariable when an error is written viaWrite-Error. Neither the common parameter-ErrorVariableworks. To still be able to collect error information I've added parameter-ErrorCollectionwhich can be used like this:$scriptErrors = [Collections.ArrayList]::new() Invoke-WithDateLog -CatchExceptions -ExceptionStackTrace -ErrorCollection $scriptErrors { Write-Error 'Write to stderr' -EA Continue throw 'Critical error' } if( $scriptErrors ) { # Outputs "Number of errors: 2" "`nNumber of errors: $($scriptErrors.Count)" }

