A week or so ago Aaron Nelson (Blog|Twitter) put out a call for help on Twitter looking for anyone that could help with adding autocomplete for looking up an email address to a PowerShell forms application. The original request was to look up the user in the Global Address List (GAL) via Outlook but after some thought we decided to switch to looking up the recipients via Active Directory (AD), allowing the search to work on machines that do not have Outlook installed…like servers. I will walk through both functions then provide a quick and dirty test application so you can try out the code for yourself.
The first function I want to show is the one to look up a recipient via Outlook. Despite its limited application this is the more interesting code block to me. I love that I only had to pass a partial name to get back the closest match from the GAL. I chose to include the instantiation of the $outlook object in this function because it made for a more clear example. If I were writing production code I would likely declare $outlook as a global variable then just instantiate it in this function if it had not been already. A great source for more information on calling into Outlook from PowerShell is this article.
The other way to get after this information is via Active Directory. My feeling is that this is going to be the preferred method for most people to look up email addresses. The exception would be those people that want to be able to look up contacts from outside their organization in their local address book. Going the AD route took a few more lines of code, but was still quite easy. The big difference here is that we had to define a search filter by applying the wildcard symbol, “*”, to the portion of the recipient name that had been typed so far. The other big thing to notice is that checks to make sure the results are not null had to be added because unlike the Outlook this search may not return any results. I found this article incredibly helpful in putting this function together.
That does it for the functions. Now for the test harness. This code is not terribly pretty and could probably be made more robust but it seems to work well enough for me to demonstrate the calls. The one thing that I had thought I would need to add is multi-threading to work like AJAX, but since the code runs so much faster than the HTTP calls you would see with AJAX it seems unnecessary. If the lookups run slowly in your environment then it would make sense to add some threading logic. With that, here is the code for the test harness:
I hope you find these functions helpful. Please let me know if you run into any issues with them or know of a better way to do the same thing. Please keep in mind that scripts from the internet are like Halloween candy, inspect before consumption. I offer no warranty beyond a sympathetic ear if you should run into any issues.