Get AD OU container.

This topic contains 7 replies, has 2 voices, and was last updated by Profile photo of fair64 fair64 2 years, 4 months ago.

  • Author
    Posts
  • #17568
    Profile photo of fair64
    fair64
    Participant

    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
    }

  • #17569
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

  • #17575
    Profile photo of fair64
    fair64
    Participant

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

  • #17576
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.)

  • #17577
    Profile photo of fair64
    fair64
    Participant

    Awesome, thanks for the explanation.

  • #17578
    Profile photo of fair64
    fair64
    Participant

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

  • #17579
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

  • #17580
    Profile photo of fair64
    fair64
    Participant

    Thanks again Dave.

You must be logged in to reply to this topic.