# FindUser1.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 ADO in PowerShell 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 = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $strRoot = $strDomain.GetDirectoryEntry() $adoConnection = New-Object -comObject "ADODB.Connection" $adoCommand = New-Object -comObject "ADODB.Command" $adoConnection.Open("Provider=ADsDSOObject;") $adoCommand.ActiveConnection = $adoConnection $adoCommand.Properties.Item("Page Size") = 100 $adoCommand.Properties.Item("Timeout") = 30 $adoCommand.Properties.Item("Cache Results") = $False $strBase = $strRoot.distinguishedName $strAttributes = "distinguishedName" $strScope = "subtree" $strFilter = "(cn=$strName)" $strQuery = ";$strFilter;$strAttributes;$strScope" $adoCommand.CommandText = $strQuery $adoRecordset = $adoCommand.Execute() Do { $adoRecordset.Fields.Item("distinguishedName") | Select-Object Value $adoRecordset.MoveNext() } Until ($adoRecordset.EOF) $adoRecordset.Close() $adoConnection.Close()