Timestamp formatting

Long time ago I hasn’t posted about some interesting issues or stories. It was a “boring” project time, mainly for Windows 10 migration where I just had always the known issues which are posted and blogged by most of the Microsoft cracks.

In this short post I’d just like to show how I was using the timestamp formatting in PowerShell and/or in an always-working batch file.

It sounds trivial, but I think if somebody had to script, effective logging is always a must. First of all if you want to troubleshoot something. At least then when the audit guy is asking you where are the log files from e.x. a logon or migration script. 🙂

When it comes to displaying dates and times, there’s no single format that works for every situation. With such wide international and regional variation in formatting, and so many situations where dates and times are used, every case is unique.

For me are important criteria for logging:

  • It can be sorted alphabetically (if you need to combine multiple logs)
  • Always has the same length
  • No AM/PM to mess things up 😉

To cut a long story short, I am using this format for example to create log files for the logon script:

[String] $logPath = $env:SystemDrive + "\Logs"
[String] $logFile = [string]::Format("{0}\{1}-{2}", $logPath, (Get-Date -Format "yyyyMMdd-HHmmss"),"LogonScript.log")

The short version could be used so:

Get-Date -Format "yyyyMMdd-HHmmss"

In these log files personally I am logging every command with the following formatting:

Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
Get-Date –Format "yyyy-MM-dd HH:mm:ss"

 

If your sever or clients are in different timezone then you should fine tune my recommendations. An international format, understandable across countries and cultures could be a following format:

Get-Date -Format o

More PowerShell tips you can find on the Microsoft Docs.

 

In ‘back to the root’ scheduled tasks or for ‘just for fun’ script I am still using command line with these commands:

SET _HH=%TIME: =0%
SET _TIME=%_HH:~0,2%%time:~3,2%%time:~6,2%
SET _DATE=%date:~-4%%date:~-7,2%%date:~-10,2%

SET LOGDIR=%SYSTEMDRIVE%\Logs
SET LOGFILE=%LOGDIR%\%_DATE%-%_TIME%-AKOSBAKOS_CH.log

ECHO Date and time is: %DATE% - %TIME% >> %LOGFILE%

 

Happy logging, Ákos

Leave a Reply

Your email address will not be published. Required fields are marked *