CSJ
CSJ

Reputation: 2957

powershell convert the date property to string when using ConvertTo-Json

I'd like to get all Hyper-V VM information from Get-VM cmdlet as below:

Get-Vm | Select-Object * | ConvertTo-Json

Where the CreationTime in each VM dictionary looks like \/Date(-11644473600000)\/", in the output

How can I make it look like this format 2017/11/29 16:09:00 in the output json?

When I guess it is the number of Epoch timestamp, I found it sometimes a negative number.

I found some articles taking about this issue which take Get-Date for example, but in my case it is a property in Get-VM that I am not sure if a faster way to convert the date property without long script to parse the output.

Upvotes: 1

Views: 2686

Answers (1)

Clijsters
Clijsters

Reputation: 4256

To select a Property based on an user defined Expression one can define them in Select-Object the following way:

Get-VM | Select-Object -Property @{Name="ReadableCreationTime"; Expression={Get-Date $_.CreationTime}}, *

This selects the user defined property ReadableCreationTime and all other properties (*).

Now, you want to exclude the original CreationTime as it is a) hard to read and b) redundant to ReadableCreationTime. This can be done using the -ExcludeProperty parameter:

Get-VM | Select-Object -Property @{Name="ReadableCreationTime"; Expression={Get-Date $_.CreationTime}}, * -ExcludeProperty CreationTime

...And pipe the result to ConvertTo-Json

Keep in mind that while reading the resulting json, you have to parse the date, because it is just a string, not a valid Date value.

Upvotes: 4

Related Questions