Using the Get-ADObject (pscx) cmdlet?

Analysis
Aug 20, 20072 mins

In an effort to post some PowerShell related stuff, and to all of those of you that think I never use PowerShell one-liners, this blog is for you. Basically, I had a friend that wanted a Windows related replacement for good old CLI based ldapsearch. Hearing me rave about PowerShell, or maybe it was all the other books, articles, blogs, etc. He set his sights on completing LDAP searches for Active Directory using PowerShell. Anyhow, to summarize the story, he contacted me and started complaining about how much it sucked having to create and use a DirectoryServices.DirectorySearcher object to complete his searches. As I state before, he wanted an ldapsearch replacement. This also translated to him wanting just one command to complete LDAP queries while being able to feed that command information through the pipeline. Err… my response was either write a function and load it up in your profile, write a cmdlet (hehe), or use the Get-ADObject cmdlet that comes with PSCX (see previous post about the PowerShell Community Extensions). Liking this response, he then asked me to complete a one liner for him using the cmdlet. The one liner he wanted went like this:

  1. Read a list of usernames from a file.
  2. For each user query their (email address, and CN).
  3. Then dump this information to another file.

The one liner to meet his need went something like this: import-csv .users.csv | foreach {Get-ADObject -filter “(&(samAccountName=$($_.userid)))”} | select @{name=’Name’;Expression={$_.cn}},@{ name=’Accountname’; Expression={$_.sAMAccountName}},@{ name=’Mail’; Expression={$_.mail}} | export-csv results.csv So what is this miracle of a cmdlet? Well, actually it’s pretty much just a front end for the DirectoryServices.DirectorySearcher class. The guys/gals at PSCX probably got tired of setting up a searcher object. So, like me, they wrote something to shorten the workload. Theirs is a cmdlet, mine was a function (which strangely enough had the same name). In either case, nothing fancy, just an effort to shorten the time it takes to complete Active Directory searches using PowerShell (also helps when building one liners). There, I can write one liners without the compulsive need of writing a script that not only completes your automation need, but also makes you coffee and walks the dogs. For all of today’s Microsoft news, visit the Microsoft Subnet.