# FindUser2.ps1 # PowerShell script to query AD for user with specified Common Name. # # ---------------------------------------------------------------------- # Copyright (c) 2011 Richard L. Mueller # Hilltop Lab web site - http://www.rlmueller.net # Version 1.0 - January 9, 2011 # # This program demonstrates how to use the # System.DirectoryServices.DirectorySearcher class to query Active # Directory. This example finds the Distinguished Name of all objects # (there could be more than one) that have a specified Common Name. # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the copyright owner above has no warranty, obligations, # or liability for such use. # Specify Common Name of user. $strName = "James K. Smith" $strDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $strDomain $objSearcher.PageSize = 100 $objSearcher.SearchScope = "subtree" # Specify attribute values to retrieve. $arrAttributes = @("distinguishedName") ForEach($strAttribute In $arrAttributes) { $objSearcher.PropertiesToLoad.Add($strAttribute) > $Null } # Filter on object with specified Common Name. $objSearcher.Filter = "(cn=$strName)" $colResults = $objSearcher.FindAll() ForEach ($strResult In $colResults) { $strDN = $strResult.Properties.Item("distinguishedName") Write-Host $strDN }