Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all computer accounts in an another domain using PowerShell?

Tags:

powershell

I am trying to get all computer accounts from the another domain.

Here is my PowerShell script:

$environment = "myDomain"
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://dc=" + $environment + ",dc=com")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher ("LDAP://dc=" + $environment + ",dc=com")
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("(objectCategory=$strCategory)")
$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)| Out-Null}  
$colResults = $objSearcher.FindAll()
 foreach ($objResult in $colResults) {
   $objComputer = $objResult.Properties
   Write-output $objComputer.name
}

I am getting this error:

Exception calling "FindAll" with "0" argument(s): "A referral was returned from the server.

How can I fix this error?

like image 227
user1018832 Avatar asked Dec 20 '25 05:12

user1018832


1 Answers

Can you try this :

$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://DCIpAddress:389/dc=dom,dc=fr","[email protected]","admin")

# Here look for a user
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
$Rech.filter = "(([email protected]))"
$Rech.SearchScope = "subtree"
$Rech.PropertiesToLoad.Add("distinguishedName");
$Rech.PropertiesToLoad.Add("sAMAccountName");  
$Rech.PropertiesToLoad.Add("lastLogon");  
$Rech.PropertiesToLoad.Add("telephoneNumber");
$Rech.PropertiesToLoad.Add("memberOf");
$Rech.PropertiesToLoad.Add("distinguishedname");
$Rech.PropertiesToLoad.Add("otherHomePhone"); # téléphone domicile autre

$liste = $Rech.FindAll()

It's the same as your code, but here I target a DC (you'd better target a domain DNS name)and I authenticate my connnexion. If the other domain is in the same forest, you can use the Enterprise admin account, if the other domain is in another forest, or in a trusted domain, use the administrator of the domain.

like image 166
JPBlanc Avatar answered Dec 23 '25 20:12

JPBlanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!