PowerShell: Get AD attributes

A while back I posted a script to monitor Active Directory LDAP response times. As part of this I had a chunk of code that not only did an LDAP lookup, but also pulled all the AD attributes into a PowerShell object. Here’s the code:

$User = $env:USERNAME
# assume that the DC is in the same domain as the user running the test
$DC = $env:LOGONSERVER.Replace("\\","")
$Root = [ADSI] ("LDAP://"+$DC+"."+$env:USERDNSDOMAIN)

$Searcher = New-Object System.DirectoryServices.DirectorySearcher $Root
$Searcher.Filter = "(cn=$User)"
# run the query
$Container = $Searcher.FindAll()

[System.Collections.Arraylist]$Names = $Container.Properties.PropertyNames
[System.Collections.Arraylist]$Properties = $Container.Properties.Values
$Obj = New-Object System.Object
for ($i = 0; $i -lt $Names.Count)
		$Obj | Add-Member -type NoteProperty -Name $($Names[$i]) -Value $($Properties[$i])
$Obj.pwdlastset = [System.DateTime]::FromFileTime($Obj.pwdlastset)
$Obj.lastlogontimestamp = [System.DateTime]::FromFileTime($Obj.lastlogontimestamp)

This entry was posted in PowerShell and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.