Attribute Scoped Queries (ASQs) in PowerShell

I'm in the process of tech-reviewing an important book (you'll want it on your shelf once it is released), and one of the things I did today was spend a while figuring out how to do Attribute Scoped Queries in PowerShell. If you develop in C# or C++, or use adfind to do your searches, those tools have supported ASQs for a long time.

I use PowerShell quite a bit for Exchange Server 2007+ maintenance tasks, but I am no expert when it comes to all of the various .NET Framework classes and methods available. In the past, when you've needed to search for all the members of a particular group (using the 'member' attribute) or all of the members of a particular address list (using the 'showInAddressBook' attribute), those particular searches could be very slow and quite inefficient.

With the Windows Server 2003 Domain Functional Level, the ASQ capability becomes available. Using a DirectorySearcher object, you can specify a particular group or a particular address book or (anything else that leads to a multi-valued attribute) and execute an efficient search against the sources to find their components. In this example, you can easily find the members of the 'Domain Admins' group in your domain (note, this is an easy one - there are others that are likely more significant for you).

$group  = New-Object System.DirectoryServices.DirectoryEntry( `
    "LDAP://CN=Domain Admins,CN=Users,DC=essential,DC=local")
$source = New-Object System.DirectoryServices.DirectorySearcher

$source.SearchRoot  = $group
$source.SearchScope = [System.DirectoryServices.SearchScope]::Base
$source.Filter      = "(objectClass=*)"

$source.PropertiesToLoad.Add("member")
$source.PropertiesToLoad.Add("sAMAccountName")

$source.AttributeScopeQuery = "member"

$results = $source.FindAll()

$results

One caveat: when searching for members of a group, ASQ does not work for the primaryGroup! So if you do a search for "Domain Users", it is likely that you will receive no responses in your result. This is NOT an error.

Until next time...

As always, if there are items you would like me to talk about, please drop me a line and let me know!

Published Monday, July 21, 2008 4:31 PM by michael
Filed under: ,

Comments

Thursday, July 24, 2008 2:05 PM by subject: exchange

# Weekend reading

Speeding Up PowerShell Startup MS08-039: Which users are vulnerable to the OWA XSS vulnerability? Reducing

Friday, January 30, 2009 5:01 PM by Recent URLs tagged Powershell - Urlrecorder

# Recent URLs tagged Powershell - Urlrecorder

Pingback from  Recent URLs tagged Powershell - Urlrecorder