Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Bulk Find ActiveDirectory Objects

I'm trying to develop a powershell script to help with AD Group Membership management. We have a handful of large groups (30k-60k+ objects) that we want to update with data from another system.

The script loads the objects that should be in the group from a text file. Each object then has to located in AD using a System.DirectoryServices.DirectorySearcher. After that each object is added to the group membership.

The script spends some 80% of its time looking up each object, is there a bulk way to find objects in AD with powershell?

Thanks!

like image 584
klyd Avatar asked Apr 30 '12 20:04

klyd


2 Answers

This is the fast way to query AD that I found in my experience, you need to change the query to find specific objects, in this code you'll find all user/person object in $objRecordSet.

$Ads_Scope_SubTree = 2        
$objConnection = new-Object  -com "ADODB.Connection"
$objCommand = new-Object -com "ADODB.Command"

$objConnection.Provider = "ADsDSOObject"
$objConnection.Open( "Active Directory Provider")
$objCommand.ActiveConnection = $objConnection

$objCommand.Properties.Item("Page Size").value = 1000
$objCommand.Properties.item("Searchscope").value = $Ads_Scope_SubTree 

$objCommand.CommandText = "Select Name From 'LDAP://DC = int, DC= my, DC = local' Where objectCategory = 'Person'" 

$objRecordSet = $objCommand.Execute()
$objRecordSet.RecordCount

More info here

like image 66
CB. Avatar answered Oct 21 '22 08:10

CB.


You perhaps can try System.DirectoryServices.Protocols (S.DS.P) the native (non managed) version is quite efficient.

Here is a PowerShell starting script :

# ADDP-Connect.PS1

Clear-Host
# Add the needed assemblies
Add-Type -AssemblyName System.DirectoryServices.Protocols

# Connexion
$serverName = "WM2008R2ENT" 
$ADDPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection $serverName

$userName = "JPB"
$pwd = "PWD"
$domain = "Dom"
$ADDPConnect.Credential = New-Object system.Net.NetworkCredential -ArgumentList $userName,$pwd,$domain

# Create a searcher
$searchTargetOU = "dc=dom,dc=fr"
$searchFilter = "(samAccountName=user1)"
$searchScope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$searchAttrList = $null

foreach($user in "user1","user2","user3")
{
  $searchFilter = "(samAccountName=$user)"
  $searchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $searchTargetOU,$searchFilter,$searchScope,$searchAttrList

  $searchResponse = $ADDPConnect.SendRequest($searchRequest)

  foreach($searchEntries in $searchResponse.Entries)
  {
    $searchEntries.DistinguishedName
  }
}
like image 1
JPBlanc Avatar answered Oct 21 '22 09:10

JPBlanc