Wednesday, August 10, 2016

PowerShell: Pull AD user information from multiple forests into CSV

Script example to discover the forests available on a domain, and retrieve user information, outputting in a CSV format. It makes use of System.DirectoryServices interface so there is no need to be a domain administrator or install additional ActiveDirectory components/features. All you need is Windows running PowerShell. I tested this on a 64bit machine.

 # Get the user's Distinguished Name   
 Function Get-UserInfo ()   
 {   
   $Target = @()  
   #Get Domain List  
   $objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()  
   $DomainList = @($objForest.Domains | Select-Object Name)  
   $Domains = $DomainList | foreach {$_.Name}  
   foreach($Domain in ($Domains))  
   {  
    Write-Host "Checking $Domain" -fore red  
    $ADsPath = [ADSI]"LDAP://$Domain"  
    $searcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)  
    $searcher.Filter = "(&(objectClass=User)(extensionAttribute1>=1)(company=SAMPLEFILTER))"   
    $searcher.SearchScope = "Subtree"  
    $searcher.PageSize = 1000  
    $searcher.PropertiesToLoad.Add("name")  
    $searcher.PropertiesToLoad.Add("sAMAccountName")  
    $searcher.PropertiesToLoad.Add("mailNickname")  
    $searcher.PropertiesToLoad.Add("altRecipient")  
    $searcher.PropertiesToLoad.Add("extensionAttribute1")  
    $searcher.PropertiesToLoad.Add("co")  
    $colResults = $searcher.FindAll()   
    foreach ($objResult in $colResults)  {
      $objItem = $objResult.Properties  
      $objUser = new-object System.Object   
      $objUser | Add-Member -MemberType NoteProperty -Name "userName" -Value ([string]$objItem.Item("name"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "login" -Value ([string]$objItem.Item("sAMAccountName"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "altRecipient" -Value ([string]$objItem.Item("altRecipient"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "mailAccount" -Value ([string]$objItem.Item("mailNickname"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "customID" -Value ([string]$objItem.Item("extensionAttribute1"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "country" -Value ([string]$objItem.Item("co"))  
      $Target += $objUser  
   }  
 }  
   $Target | select userName, login, alternateRecipient, mailAccount, customID, co | Export-csv "c:temp\QueryUser.csv"  
 }   
 Get-UserInfo  

No comments:

Related Posts Plugin for WordPress, Blogger...