This is actually a known issue, see: #13598
Add a -DateKind parameter to ConvertFrom-Json to control how System.DateTime / System.DateTimeOffset values are constructed. Yet I think there is no easy solution for this. One thing you might do is just invoke (Windows) PowerShell. Which isn't currently straights forward as well therefore I have created a small wrapper to send and receive complex objects between PowerShell sessions (see also my #18460 Invoke-PowerShell
purpose):
function Invoke-PowerShell ($Command) {
$SerializeOutput = @"
`$Output = $Command
[System.Management.Automation.PSSerializer]::Serialize(`$Output)
"@
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($SerializeOutput)
$EncodedCommand = [Convert]::ToBase64String($Bytes)
$PSSerial = PowerShell -EncodedCommand $EncodedCommand
[System.Management.Automation.PSSerializer]::Deserialize($PSSerial)
}
用途:
Invoke-PowerShell { '{ "date":"2022-09-30T07:04:23.571+00:00" }' | ConvertFrom-Json }
date
----
2022-09-30T07:04:23.571+00:00
更新
正如100 comments 的那样,我显然把答案复杂化了.
通过Powershell.exe调用是一种实用的解决方法(尽管速度很慢且仅适用于Windows),但请注意,您不需要帮助器函数:如果将script block传递给Powershell.exe(或pwsh.exe)from PowerShell,则基于Based64 CLIXML的序列化将在后台自动发生:出于这个原因,try powershell.exe -noprofile { $args | ConvertFrom-Json } -args '{ "date":"2022-09-30T07:04:23.571+00:00" }'
,我认为没有必要使用Invoke-PowerShell cmdlet.
$Json = '{ "date":"2022-09-30T07:04:23.571+00:00" }'
powershell.exe -noprofile { $args | ConvertFrom-Json } -args $Json
date
----
2022-09-30T07:04:23.571+00:00