Problem
You want to search for a specific computer account, but don’t know its DN.
Solution
To search for a computer account, use the [adsi] type shortcut to bind to a container that holds the account in Active Directory, and then use the System. DirectoryServices.DirectorySearcher class from the .NET Framework to search for the account:
$domain = [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM" $searcher = NewObject System.DirectoryServices.DirectorySearcher $domain $searcher.Filter = '(&(objectClass=Computer)(name=kenmyer_laptop))'
$computerResult = $searcher.FindOne() $computer = $computerResult.GetDirectoryEntry()
Discussion
When you don’t know the full DN of a computer account, the System. DirectoryServices.DirectorySearcher class from the .NET Framework lets you search for it.
You provide an LDAP filter (in this case, searching for computers with the name of kenmyer_laptop), and then call the FindOne() method. The FindOnel() method returns the first search result that matches the filter, so we retrieve its actual Active Directory entry. Although the solution searches on the computer’s name, you can search on any field in Active Directory—the sAMAccountName and operating system characteristics (operatingSystem, operatingSystemVersion, operatingSystemServicePack) are other good choices.
When you do this search, always try to restrict it to the lowest level of the domain possible. If you know that the computer is in the Sales OU, it would be better to bind to that OU instead:
$domain = [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"
For more information about the LDAP search filter syntax, search http://msdn. microsoft.com for “Search Filter Syntax.”