Forum Discussion

robmo's avatar
robmo
Brass Contributor
Feb 17, 2023

Checking if a computer is in the the Active Directory global catalog

Hi,

I need a script that can tell me if a computer is found in the Active Directory global catalog. The code below is returning inaccurate results. Every computer that failed the Try statement can be found in Active Directory when I search manually. Does anyone see the problem with this example?

Import-Module ActiveDirectory
$server = "myserver.com:3268"

#Get the list of computers to test
$computers = Get-Content -Path "$PSScriptRoot\computers.txt"

#Check active directory for each computer
foreach($computer in $computers) {

    try{
        $test = Get-ADComputer $computer -Server $server

        if($null -ne $test) {
            Write-Host "$computer in AD" -ForegroundColor Green
        }
    } 

    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
        Write-Host "$computer not in AD" -ForegroundColor Red
    }
}

Thank you!

Rob

  • I added some bogus computer names to computers.txt along with some known computers and it seems to be working now. Let me know if this solution doesn't seem correct.

     

    Import-Module ActiveDirectory
    $server = "myserver.com:3268"
    
    #Get the list of computers to test
    $computers = Get-Content -Path "$PSScriptRoot\computers.txt"
    
    #Check active directory for each computer
    foreach($computer in $computers) {
    
        $test = Get-ADComputer -Filter 'Name -eq $computer' -Server $server
    
        if($null -ne $test) {
            Write-Host "$computer in AD" -ForegroundColor Green
        } else {
            Write-Host "$computer not in AD" -ForegroundColor Red
        }
    
    }

     

  • robmo's avatar
    robmo
    Brass Contributor

    Changing Line 11 to the example below appears to show the correct results. Would this change be reliable?

    $test = Get-ADComputer -Filter 'Name -eq $computer'
    • robmo's avatar
      robmo
      Brass Contributor

      I added some bogus computer names to computers.txt along with some known computers and it seems to be working now. Let me know if this solution doesn't seem correct.

       

      Import-Module ActiveDirectory
      $server = "myserver.com:3268"
      
      #Get the list of computers to test
      $computers = Get-Content -Path "$PSScriptRoot\computers.txt"
      
      #Check active directory for each computer
      foreach($computer in $computers) {
      
          $test = Get-ADComputer -Filter 'Name -eq $computer' -Server $server
      
          if($null -ne $test) {
              Write-Host "$computer in AD" -ForegroundColor Green
          } else {
              Write-Host "$computer not in AD" -ForegroundColor Red
          }
      
      }

       

Resources