Debra
Debra

Reputation: 207

Year wrong using Powershell script to pull dates from AD

I am using Powershell to pull simple data from AD. The script pulls usernames from a text file and is similar to:

Import-Module ActiveDirectory

Get-Content c:\temp\userlist.txt | Foreach-Object {
$user = $_
$fullname = (Get-ADuser -identity $user | foreach {$_.Name})
$email = (Get-ADUser -identity $user -properties * | foreach {$_.mail})
$lastlog = (Get-ADUser -identity $user -properties * | foreach {$_.lastLogon})
$lastlogstr = (Get-Date -format "yyyy MMM d" $lastlog)
"$user,$fullname,$email,$lastlog,$lastlogstr"
}

When I run this, all the correct data is pulled, and I'll see (for example)

XXXXX,John Smith,[email protected],130252373811789928,0413 Oct 2

When I check Active directory, and use the Attribute editor to view "lastLogon", I see

10/2/2013 8:29:41PM Central Daylight Time

and if I click to View that field, I see 130252373811789928 as shown above.

But for absolutely every user I query, and no matter how I format the date (i.e. as above, using D, etc.) it -always- puts in 0413 instead of 2013. Similarly, it shows 0411 for 2011, etc.

I cannot imagine why this is happening. Powershell is being run from a Windows 7 system, and I have tried using both the ISE and the powershell command.

Upvotes: 1

Views: 1859

Answers (1)

JPBlanc
JPBlanc

Reputation: 72640

Can you try :

$date = [datetime]::fromfiletime($lastlog)
$date.ToString("yyyy MMM d")

or

$date = [datetime]::FromFileTimeUtc($lastlog)
$date.ToString("yyyy MMM d")

In ActiveDirectory Microsoft specifics attibuts that deal with time are stored as a Windows file time. It's a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).

Upvotes: 3

Related Questions