Saturday, May 19, 2007

Powershell, The Best Date Format for Logs?

I admit, I used to use (get-date).tostring("yyyyMMddHHssmm") when writing timestamps to log. Using this format has several advantages –
- Can be sorted alphabetically (if you need to combine multiple logs)
- Always has same length
- No AM/PM to mess things up ;)
- An international format, understandable across countries and cultures

Then I discovered that it was not necessary to use the programming style above. Get-Date has a –format, so I could change it to Get-Date –f yyyyMMddHHmmss

This is actually ok, but maybe this is more readable –
Get-Date –f "yyyy-MM-dd HH:mm:ss"

Finally, I just realized, that there is a even simpler way of doing it and it even adds timezone and milli-seconds –
Get-Date –f o

So
"$(Get-Date –f o) Start logging"

5 comments:

Anonymous said...

Thanks a lot

@johnpkiffmeyer said...

Heads up: Colon (':') is an illegal character in file names on windows. If you use the string returned by "get-date -f o" in a log file's name and try to use it with tee-object, out-file, etc, you'll an error like, "out-file : The given path's format is not supported."

Anonymous said...

In order to clear out the odd characters from the o format, I used the following line of code:
(((Get-Date -Format o).Replace("T","-")).Replace(":","")).Substring(0,17)

This yields a string like 2012-07-10-132011 that can be easily used in a Windows file name.

Per Østergaard said...

Well, if you want to sanitize the output, it makes more sense to avoid it in the first place using Get-Date -f yyyy...

If you want -f o and sanitize it, use the simpler PowerShell operator -replace:

(Get-Date -f o) -replace '[t:.+]','-'

Unknown said...

Well, this is why PowerShell is weak. It's promises fall short in everyday usage.