PowerShell 5.1:如何将LastBootUpTime转为指定DateTime格式输出?
问题:PowerShell 5.1中ConvertTo-Json输出DateTime格式异常的解决办法?
我编写了如下函数用于获取指定服务器的最新开机时间:
Function Get-Upt { $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime $uptObj = @{LatestUptime = $upt} $uptJSON = $uptObj | ConvertTo-Json Write-Host $uptJSON $lineBreak }
但在仅安装Windows PowerShell 5.1的服务器上(因新版本下载遇到问题),输出的开机时间格式为:
{ "LatestUptime": "/Date(1749570857500)/" }
我希望将其转换为2025-06-10 14:30:45这样的DateTime格式,请问是否有可用的Cmdlet或属性可以解决该问题?
解决方案
在PowerShell 5.1中,ConvertTo-Json会将DateTime对象序列化为微软旧版JSON日期格式(/Date(ticks)/),要得到指定的字符串格式,只需在序列化前将DateTime对象转换为目标格式的字符串即可。
修改后的函数
Function Get-Upt { $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime # 将DateTime对象格式化为指定的字符串格式 $formattedUpt = $upt.ToString("yyyy-MM-dd HH:mm:ss") $uptObj = @{LatestUptime = $formattedUpt} $uptJSON = $uptObj | ConvertTo-Json Write-Host $uptJSON }
替代实现(使用Get-Date)
也可以通过Get-Date命令完成格式化,效果一致:
Function Get-Upt { $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime $formattedUpt = Get-Date $upt -Format "yyyy-MM-dd HH:mm:ss" $uptObj = @{LatestUptime = $formattedUpt} $uptJSON = $uptObj | ConvertTo-Json Write-Host $uptJSON }
关键说明
LastBootUpTime返回的是DateTime类型对象,PowerShell 5.1的ConvertTo-Json默认会将这类对象序列化为/Date(ticks)/格式。- 通过
ToString()或Get-Date -Format将DateTime对象转换为字符串后,ConvertTo-Json会直接保留该字符串内容,输出你需要的yyyy-MM-dd HH:mm:ss格式。
内容的提问来源于stack exchange,提问作者mimi m
相关产品推荐
相关产品推荐

