Get AD OU container.

I am trying to get the Server OU location from a list of server. The code I wrote works but dose not seem to be very efficient. Is there a better way of coding this?
Thanks in advance.

Import-Module ActiveDirectory
$servers = Get-Content c:\serverlist.txt

foreach ($serv in $servers)
{
$result = Get-ADComputer -server dc2 $serv | select distinguishedname
$result | ft -AutoSize | Out-File c:\result.txt -Append
}

You could probably build a single query to the domain controllers, instead of calling Get-ADComputer once for each. Something along these lines:

Import-Module ActiveDirectory
$servers = Get-Content c:\serverlist.txt

$queryStrings = $servers | ForEach-Object { "SamAccountName -eq '$_`$'" }
$filter = $queryStrings -join ' -or '

Get-ADComputer -Filter $filter |
Format-Table -Property DistinguishedName -AutoSize |
Out-File c:\result.txt -Append

That should be faster overall, but you do need to be aware of how much time it takes for a single query to run. AD queries with very large result sets sometimes wind up timing out, but that shouldn’t become a problem unless you have many thousands of computers in that text file.

Thanks Dave just what I was looking for.
Whats the -join ’ -or ’ for?

That turns an array of strings into a single string, separated by ’ -or '. In this case, we’re building a filter string such as SamAccountName -eq ‘Computer1$’ -or SamAccountName -eq ‘Computer2$’ -or SamAccountName -eq ‘Computer3$’ (where Computer1, Computer2 and Computer3 are the strings that came out of your text file.)

Awesome, thanks for the explanation.

One more quick question Dave, goggled for it but couldn’t find anything on it . I know that $_ feeds the current object in the pipeline but why is every computername appended with the $ ?

That’s an Active Directory thing, not specific to PowerShell. The SamAccountNames of computer accounts (as well as domain trust accounts, managed service accounts, and possibly some other types I’m forgetting) always end with a $ symbol.

Thanks again Dave.