This PowerShell Script can be used to search Active Directory using an input file (OU.csv).
Input file contains the distinguishedname of the OU in the following format:\
Dn
"ou=Site1, ou=Users, dc=domain, dc=com”
"ou=Site2, ou=Users, dc=domain, dc=com
Make sure to the DN as the header in the input file – OU.csv
More Info - http://portal.sivarajan.com/2011/07/search-active-directory-get-user.html
# Search Active Directory and Collect User Information
#
# www.sivarajan.com
#
clear
$UserInfoFile = New-Item -type file -force "C:\Scripts\UserInfo.txt"
"samaccountname`tgivenname`tSN" | Out-File $UserInfoFile -encoding ASCII
Import-CSV "C:\Scripts\OU.csv" | ForEach-Object {
$dn = $_.dn
$ObjFilter = "(&(objectCategory=User)(objectCategory=Person))"
$objSearch = New-Object System.DirectoryServices.DirectorySearcher
$objSearch.PageSize = 15000
$objSearch.Filter = $ObjFilter
$objSearch.SearchRoot = "LDAP://$dn"
$AllObj = $objSearch.FindAll()
foreach ($Obj in $AllObj)
{ $objItemS = $Obj.Properties
$Ssamaccountname = $objItemS.samaccountname
$SsamaccountnameGN = $objItemS.givenname
$SsamaccountnameSN = $objItemS.sn
"$Ssamaccountname`t$SsamaccountnameGN`t$SsamaccountnameSN" | Out-File $UserInfoFile -encoding ASCII -append
}
}
# Search Active Directory and Collect User Information # # www.sivarajan.com # clear $UserInfoFile = New-Item -type file -force "C:\Scripts\UserInfo.txt" "samaccountname`tgivenname`tSN" | Out-File $UserInfoFile -encoding ASCII Import-CSV "C:\Scripts\OU.csv" | ForEach-Object { $dn = $_.dn $ObjFilter = "(&(objectCategory=User)(objectCategory=Person))" $objSearch = New-Object System.DirectoryServices.DirectorySearcher $objSearch.PageSize = 15000 $objSearch.Filter = $ObjFilter $objSearch.SearchRoot = "LDAP://$dn" $AllObj = $objSearch.FindAll() foreach ($Obj in $AllObj) { $objItemS = $Obj.Properties $Ssamaccountname = $objItemS.samaccountname $SsamaccountnameGN = $objItemS.givenname $SsamaccountnameSN = $objItemS.sn "$Ssamaccountname`t$SsamaccountnameGN`t$SsamaccountnameSN" | Out-File $UserInfoFile -encoding ASCII -append } }