Locating AD Computer Objects with PowerShell

Yesterday I was asked how you can find the locations of a list of computer objects in the Active Directory. Not an issue if all of your computers are in Computers, but we’ve got a structure of OUs that would put any ant colony to shame, so it’s a valid question.


My answer was as follows:


Put your list of machines in a file (c:\temp\machine.txt – one computer name per line) and depending on where you’re going to run this it’s a bit different. If you were on a Server 2008 R2 server which has the Active Directory cmdlets, then you need to do:


Get-Content c:\temp\machine.txt | Foreach-Object{
Get-ADComputer $_
} | Select-Object name,@{
name=”ou”;expression={
$_.distinguishedname.substring($_.name.length+4)
}
} | Format-Table -AutoSize


If not, I would suggest installing the AD cmdlets from Quest (http://www.quest.com/powershell/activeroles-server.aspx) and doing this:


Get-Content c:\temp\machine.txt | Foreach-Object{
Get-QADComputer $_
} | Select-Object name,parentcontainer | Format-Table –AutoSize



I’m just outputting to a table because I wasn’t told how the output was going to be used. You could use Export-Csv instead to pop it in a file. I should also point out that each of those examples works as a single line of code. I’ve just put it on different rows to stop my blog wrapping it in a confusing place – they’re actually pretty easy to read as a single line.


Now those are the ways that I would do it, but if you have to do something without the Microsoft or Quest AD cmdlets (if your environment is really locked down), all is not lost. This should work anywhere in your domain you can run PowerShell:


$ds = New-Object DirectoryServices.DirectorySearcher
$ds.SearchRoot=”LDAP://DC=yourdomain,DC=com”
Get-Content c:\temp\machine.txt | Foreach-Object{
$ds.Filter=”(&(objectclass=computer)(name=$_))”
$ds.FindOne() | Select-Object path

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>