Converting Epoch Time to Human Readable Time in Powershell 'ConvertTo-Json' Outputs

404 views Asked by At

Powershell automatically converts all the date-time fields to Epoch time when using 'ConvertTo-Json'. Is there a way to prevent this from happening or changing it back to human-readable date-time? For example, check some of the fields in the output

Command:

Get-LocalUser | ConvertTo-Json

Output:

"PasswordChangeableDate":  "\/Date(1597311158786)\/",
"PasswordExpires":  null,
"UserMayChangePassword":  true,
"PasswordRequired":  true,
"PasswordLastSet":  "\/Date(1597224758786)\/",
"LastLogon":  "\/Date(1597238163431)\/",

Is there a way to prevent Powershell from converting the above fields into Epoch time, or converting them back to human-readable date-time?

1

There are 1 answers

0
user459872 On

I suspect that you are using Powershell 5 version. In Powershell 5 ConvertTo-Json cmdlet is implemented using the JavaScriptSerializer class. See this table to know the mapping between managed types and JSON equivalent.

Managed type JSON equivalent
DateTime Date object, represented in JSON as "/Date(number of ticks)/". The number of ticks is a positive or negative long value that indicates the number of ticks (milliseconds) that have elapsed since midnight 01 January, 1970 UTC.The maximum supported date value is MaxValue (12/31/9999 11:59:59 PM) and the minimum supported date value is MinValue (1/1/0001 12:00:00 AM).

One solution I could think of is to convert the date to string(Using ToString()) before serializing to JSON or to upgrade to Powershell 7 :). This is because PowerShell 7 uses Newtonsoft Json.NET under the hood and the default format used by Json.NET is the ISO 8601 standard: "2012-03-19T07:22Z".