PowerShell - search AD for Computer Object in List

howbs2002 106 Reputation points
2021-03-18T23:07:37.26+00:00

I am trying to ascertain if server accounts in a text file exist in AD, but I only get the result - "server does not exists in AD" even for servers that do exist.

Please help me figure out what I have missed:

**foreach ($server in (Get-Content C:\Scripts\servers.txt)) {
  try{
    $test = Get-ADComputer -Identity $server -ErrorAction Stop
    if($test){
      Write-Output "Server object $server exists in AD" | Out-File C:\Scripts\AD_result.txt -Append
    }
  }catch{
    Write-Output "Server object $server does not exist in AD" | Out-File C:\Scripts\AD_result.txt -Append
  }
}**
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 Reputation points
    2021-03-19T01:41:07.227+00:00

    What's in your servers.txt file? If you're using the "-Identity" parameter in the Get-ADComputer that parameter only accepts a distinguishedName, a GUID, a SID, or a sAMAccount as a value. If your file contains only the names of computers you'll have to use -Filter instead of -Identity.

    Assuming you have just computer names in that file, your script should look something like this:

    foreach ($server in (Get-Content C:\Scripts\servers.txt)) {
        $test = Get-ADComputer -Filter { Name -eq $server }
        if ($test) {
            Write-Output "Server object $server exists in AD" | Out-File C:\Scripts\AD_result.txt -Append
        }
        else {
            Write-Output "Server object $server does not exist in AD" | Out-File C:\Scripts\AD_result.txt -Append
        }
    }
    

    When you use a filter there should never be an exception, so there's need/benefit to using a Try/Catch. Instead, just test the result to see if anything was returned.


1 additional answer

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,121 Reputation points Microsoft Vendor
    2021-03-19T07:35:02.987+00:00

    Hi,

    What are the ’server accounts‘ in the text file?You can check the value of $server in the foreach loop.

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments