Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell 5.1 DateTime Format

Tags:

powershell

I have this function to retrieve the latest uptime on a certain server.

Function Get-Upt { 
  $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime

  $uptObj = @{LatestUptime = $upt}
  $uptJSON = $uptObj | ConvertTo-Json
  Write-Host $uptJSON
  $lineBreak

}

The problem I have is that on some servers I only have Windows Powershell 5.1 (because I've been having some trouble downloading the newer version), and the output I get for the uptime looks like this:

{
    "LatestUptime":  "\/Date(1749570857500)\/"
}

but I want it to have the DateTime format (like this):

2025-06-10 14:30:45

Is there a cmdlet or some kind of property I can use to fix this?

like image 336
mimi m Avatar asked Oct 14 '25 03:10

mimi m


1 Answers

If you want a similar date time format as the one used by the JSON serializer in PowerShell 7+, you can convert your DateTime to string using the o format:

function Get-Upt {
    $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
    @{ LatestUptime = $upt.ToString('o') } | ConvertTo-Json
}
like image 143
Santiago Squarzon Avatar answered Oct 17 '25 08:10

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!