none
Find server in AD exists using powershell RRS feed

  • Question

  • Can some one help me out to find an OU in which the computer account exists using powershell? 

    Exemple:

    $computerName = "HOST-ES01"
    $found = $FALSE
    $domain = [ADSI]("LDAP://dc=dicasquefunfa,dc=dqf)
    
    $ous = ($domain.psbase.children |
            Where-Object {$_.psBase.schemaClassName -eq "OrganizationalUnit"} |
            Select-Object -expand Name)        
    
    foreach ($child in $ous){
        $ou = [ADSI]("LDAP://ou=$child,dicasquefunfa,dc=dq")
        $computers = ($ou.psbase.children |
                      Where-Object {$_.psBase.schemaClassName -eq "Computer"} |
                      Select-Object -expand Name)
    
        foreach ($client in $computers){
            if ($client -eq $computerName) {
                Write-Host "Found $computerName in" $ou.psBase.name
                $found = $TRUE
            }
        }
    }
    
    if (-not $found) {Write-Host "$computerName not found."}

    I want to go with a list of machines and see whether there is in the field
    example:
    Input_Hosts.txt
    Output_Host.txt

    Thursday, August 27, 2015 3:11 PM

Answers

  • This isn't a "script on demand" forum, but here is an example:

    Import-Module ActiveDirectory -ErrorAction Stop
    
    Get-Content "Input_hosts.txt" | ForEach-Object {
      $dn = Get-ADComputer $_ | Select-Object -ExpandProperty DistinguishedName
      New-Object PSObject -Property @{
        "ComputerName" = $_
        "OU" = Get-ADPathname -Path $dn -RemoveLeafElement
      }
    } | Export-Csv "List.csv" -NoTypeInformation
    

    This script uses Get-ADPathname.ps1 from here:

    Windows IT Pro: Use PowerShell to Handle Active Directory Paths


    -- Bill Stewart [Bill_Stewart]

    Thursday, August 27, 2015 3:49 PM
    Moderator