Converting UNIX Time

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

Surprisingly, when you read some values from the Windows Registry, they do not seem to be in a readable format:

$key = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'
Get-ItemProperty $key | 
  Select-Object -ExpandProperty InstallDate

The InstallDate value returns as a large number. It turns out that Windows stores its install date in UNIX format which are the seconds since 1/1/1970. Here is a little function that converts this back to real dates:

function ConvertFrom-UnixTime {
  param(
      [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [Int32]
    $UnixTime
  )
  begin {
    $startdate = Get-Date Date '01/01/1970' 
  }
  process {
    $timespan = New-Timespan -Seconds $UnixTime
    $startdate + $timespan
  }
}

So now, you can correctly read the installation date from the registry:

$key = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'
Get-ItemProperty $key | 
  Select-Object -ExpandProperty InstallDate |
  ConvertFrom-UnixTime

If you wanted to know how many days your Windows is old, add some more PowerShell cmdlets:

$key = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'
Get-ItemProperty $key | 
  Select-Object -ExpandProperty InstallDate |
  ConvertFrom-UnixTime |
  New-TimeSpan |
  Select-Object -ExpandProperty Days

Twitter This Tip! ReTweet this Tip!


Posted Mar 09 2012, 06:00 AM by ps1

Comments

Laurent Schneider wrote re: Converting UNIX Time
on 03-09-2012 11:41 AM

sounds excellent to convert from universal time, but to get a difference in days I would not refer to 1970

[int](((get-date -u %s)-(Get-ItemProperty 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'

| Select-Object -ExpandProperty InstallDate))/86400)

ymmv

Copyright 2012 PowerShell.com. All rights reserved.