Adding a Timestamp to a Pipeline of Strings

If I'm doing something long-running, and I want it to know when various lines of output are generated, assuming they are being sent to STDOUT (something PSH is NOT good at), here's a quick way to preface the output with a timestamp.

-Format allows us to pass a formatting parameter to Get-Date.

-AsObject returns the output as a series of PSCustomObjects instead of Strings.

-All outputs blank lines, which are normally excluded.



function Add-TimeStamp {
     param (
         [string]$Format = $null,
     process {
         $input | % {
             if ([string]$_ -or $All) { 
                 $object = [System.Object] | Select-Object -Property Time, String;
                 if ($Format) {
                     $object.Time = Get-Date -Format $format;
                 } else {
                     $object.Time = Get-Date;
                 $object.String = $_.ToString();
                 if ($AsObject) {
                 } else {
Comments (0)

Skip to main content