Author Posts

July 29, 2014 at 7:30 am

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
}

July 29, 2014 at 7:40 am

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.

July 29, 2014 at 9:14 am

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

July 29, 2014 at 9:24 am

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

July 29, 2014 at 9:33 am

Awesome, thanks for the explanation.

July 29, 2014 at 10:13 am

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 $ ?

July 29, 2014 at 10:15 am

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.

July 29, 2014 at 10:21 am

Thanks again Dave.