question

howbs2002-5879 avatar image
0 Votes"
howbs2002-5879 asked howbs2002-5879 commented

PowerShell - search AD for Computer Object in List

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered howbs2002-5879 commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.