Wednesday, October 15, 2014

Adventures in PowerShell: Converting UTC to DateTIme

Intro

Ran into a problem recently. I'm working on script (more on this later) that will let me pull a list of user profiles on a remote machine. The problem is that the user profile's "last use time" a bit of information I would like to have is in UTC format System.String object -- meaning it looks like this:

20141015160319.191919+000
Pretty standard stuff. Except PowerShell doesn't know what to do with it. It blew my mind when I learned this. PowerShell doesn't have a native function to convert this type of string to a date (that is, a 'System.DateTime' object. So after an hour of Googling I couldn't find a good go-to script to handle it (at least, not one in PowerShell, several in VB or C#). So I wrote my own. It's a pretty simple script, it relies on it being in the specific format above, that is:

yyyyMMddhhmmss.ffffffzzz
 I may update this script if I find additional formats -- but being a standard, this should work in most places.

One note is that while the format specifies down 6 decimal places, windows can only handle 3, so the trailing 3 are dropped.

This will convert to your local timezone with the '-ToLocal' flag


The Code:

function Convert-UTCtoDateTime{
<#

  Author: Keith Ballou
  Date: 10/15/14

#>

    #Parameter Binding
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True,Position=1)][string]$UTC,
        [Parameter(Mandatory=$false)][switch]$ToLocal
        )

    #Breakout the various portions of the time with substring
    #This is very inelegant, and UTC
    $yyyy = $UTC.substring(0,4)
    $M = $UTC.substring(4,2)
    $dd = $UTC.substring(6,2)
    $hh = $UTC.substring(8,2)
    $mm = $UTC.substring(10,2)
    $ss = $UTC.substring(12,2)
    $fff = $UTC.substring(15,3)
    $zzz = $UTC.substring(22,3)

    #If local, add the UTC offset returned by get-date
    if($ToLocal){
    (get-date -Year $yyyy -Month $M -Day $dd -Hour $hh -Minute $mm -Second $ss -Millisecond $fff) + (get-date -format "zzz")
    }
    #else just return the UTC time
    else{
    get-date -Year $yyyy -Month $M -Day $dd -Hour $hh -Minute $mm -Second $ss -Millisecond $fff
    }
}

No comments:

Post a Comment