Get Computers in OU’s

Hello,

Hereunder a quick PowerShell function to retrieve all the computer names in one or more given OU in the current domain :

Function Get-ComputersInOU{
    [CmdletBinding()]
    Param(
        [Parameter(Position=1,
            Mandatory=$false,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$True,
            HelpMessage='Provide a OU DistinguishedName')]
        [String[]]$OUs
    )

    Begin{
        [String[]]$Server=$null
    }
    Process{
        ForEach($OU in $OUs){
            Write-Verbose -Message "Processing $OU..."
            $Searcher=[adsisearcher]"objectClass=Computer"
            $Searcher.searchroot.Path="LDAP://$OU"
            [void]$Searcher.PropertiesToLoad.Add('Name')
            $Servers+=$Searcher.FindAll() | % {$_.Properties.name}
        }
    }
    End{
        $Servers
    }
}

You can use it like :

  1. “OU=Finance,DC=AD,DC=ItForDummies,DC=net”,”OU=HR,DC=AD,DC=ItForDummies,DC=net” | Get-ComputersInOU -Verbose
  2. Get-ComputersInOU -OUs “OU=HR,DC=AD,DC=ItForDummies,DC=net” | Out-GridView
  3. Get-ComputersInOU -OUs “OU=HR,DC=AD,DC=ItForDummies,DC=net” | ForEach-Object -Process { Test-Connection -ComputerName $_ -Count 1}

Note : This function does not need the Active Directory PowerShell module, so it can be used on any domain, you only need PowerShell 2 minimum.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.