Get an Active Directory Property from Powershell

June 27, 2008

In an earlier post I mentioned a useful link for Powershell users.  I am happy to say I used the cheat sheet today.

Sometimes you want to grab a property from an Active Directory entry.  I wanted to be able to do it from Powershell.

One of the cool things about PowerShell is that you can access the Namespaces in the .net framework.  So you can put together a script that can access Active Directory the same way you do it from .net Code using Directory Services.

Here is what I came up with:

Write-Host “”
$id = Read-Host “Which username?”
$prop = Read-Host “Which Property(Leave blank for all or type ‘list’ for property names)?”

$de = new-object directoryservices.directoryentry(“LDAP://your_LDAP_path“)
$ds = new-object directoryservices.directorysearcher($de)
$ds.filter = ‘(&(samaccountname=’ + $id + ‘))’
$results = $ds.findall()

if ($prop -eq “”)
{
Write-Host “”
$results.item(0).properties | more
}
elseif ($prop -eq “list”)
{
Write-Host “”
$results.item(0).properties.propertynames | more
}
else
{
Write-Host “”
$results.item(0).properties.item($prop)
}
Write-Host “”
Write-Host “”

So you just save this script as your_filename.ps1 and run it.

The LDAP filter is set to filter by the “samaccountname” which is usually the user name/id of the user.  If you wanted to filter by something else you could do so by changing the filter string.

After you run it you will be prompted for the variables and presto!  Some kick-assery ensues.

Leave a comment