Has Invoke-RestMethod changed in v7.x?

I’m testing an existing PowerShell module that uses a third party REST API. With PowerShell 5.1, the module correctly returns json with an embedded date string in UTC format, as expected.

However, when using PowerShell 7.x, the UTC string is automatically converted to the local time format within the json output. Is there a way to prevent this automatic conversion of date strings?

It’s not Invoke-RestMethod that’s changed but ConvertFrom-JSON. From version 6, it attempts to convert strings formatted as timestamps to DateTime values. This causes the UTC information to be lost.

PowerShell 5.1
PS E:\Temp> {‘2020-12-27T11:15:00.246+05:30’} | ConvertFrom-Json

2020-12-27T11:15:00.246+05:30

PowerShell 7.2
PS E:\Temp> {‘2020-12-27T11:15:00.246+05:30’} | ConvertFrom-Json

27 December 2020 05:45:00

There is an open feature request to add a -DateKind parameter to ConvertFrom-JSON.

https://github.com/PowerShell/PowerShell/issues/13598

This explains it. Thanks Matt

As a follow up, its not just ConvertFrom-Json - it affects Invoke-RestMethod also. In my code, I have something similar to:

$Response = Invoke-RestMethod @PSboundParameters
$Response | ForEach-Object {
$_.utcdate
}

This also converts the date in PowerShell 7.x, rather than passing the original UTC date string ( e.g. ‘2020-01-03:10:20:20+11.00’), as Windows PowerShell does. So, I’m hoping they also add date conversion suppression to Invoke-RestMethod also.

Actually, IMO they should leave the default behavior alone and add a parameter to these cmdlets to do the date conversion, if that’s what you need.

For now, I’m converting the date object back to the original string, using:

$DateStr = Get-Date -Date $_.utcdate -Format ‘yyyy-MM-ddThh:mm:sszzz’

That’s interesting. In my testing, I connected to a service that sent dates in the response and the response was always the original timestamp in the raw data, it was only when processed by ConvertFrom-Json that the format changed.

I was using this API for testing: https://gorest.co.in/public-api/users if you want to try.

Pretty sure that Invoke-RestMethod uses ConvertFrom-Json to automatically parse responses to a PSObject. If you wanted to avoid the parsing, you would have to use Invoke-WebRequest to get straight JSON returned. Not sure why they would do automatic date conversion to local time, that is just silly, just convert the date and let the user do conversions if they wanted.