Home > Software engineering >  When running a command in powershell how can I prepend a date/time for all output on stdout/stderr?
When running a command in powershell how can I prepend a date/time for all output on stdout/stderr?

Time:05-29

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:

Have you tried inspecting the Console Output

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 -CatchExceptions to catch exceptions and log them like regular non-terminating errors. Pass -ExceptionStackTrace to 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 $Error variable when an error is written via Write-Error. Neither the common parameter -ErrorVariable works. To still be able to collect error information I've added parameter -ErrorCollection which 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)"
    }
    
  • Related