Tuesday, July 22, 2008

Working with Active Directory Dates

Recently, my friend and colleague asked me about how to limit an ldap search to only return objects that were created after a certain date. 'whenCreated' should be a logical choice to solve that. However, this attribute has an interesting format, see this reference. So, i marked up a few functions to help us work with the date naturally within Powershell.
function ConvertToAdDate([DateTime]$date) {
"{0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}.0Z" -f $date.year,$date.month, `
$date.day, $date.Hour, $date.Minute, $date.Second
}
function ConvertFromAdDate([String] $date) {
$pattern = `
'^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(?<hrs>\d{2})`
(?<min>\d{2})(?<sec>\d{2})\.0Z$
'
$match = [regex]::Match($date,$pattern)
if ($match.success) {
$result = New-Object System.DateTime($match.groups["year"].value,`
$match.groups["month"].value,$match.groups["day"].value,`
$match.groups["hrs"].value,$match.groups["min"].value, `
$match.groups["sec"].value,[DateTimeKind]::Utc)
$result.ToLocalTime()
}
else {
$null
}
}

No comments: