Guest User

Get all email addresses in AD

a guest
Jul 26th, 2016
562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $searchfilter = {
  2. (EmailAddress -like "*") -or
  3. (extensionAttribute14 -like "*") -or
  4. (extensionAttribute15 -like "*") -or
  5. (mail -like "*") -or
  6. (msExchShadowProxyAddresses -like "*") -or
  7. (msRTCSIP-PrimaryUserAddress -like "*") -or
  8. (personalPager -like "*") -or
  9. (proxyAddresses -like "*") -or
  10. (targetAddress -like "*") -or
  11. (UserPrincipalName -like "*")
  12. }
  13. $properties = "SamAccountName","EmailAddress","extensionAttribute14","extensionAttribute15","mail","msExchShadowProxyAddresses","msRTCSIP-PrimaryUserAddress","personalPager","proxyAddresses","targetAddress","UserPrincipalName"
  14. $adusersemails = Get-ADUser -Filter $searchfilter -Properties $properties | select $properties
  15. $results = @()
  16. foreach ($user in $adusersemails) {
  17.     foreach ($singleproperty in $properties) {
  18.         if ($user.($singleproperty) -notlike "") { #iterate through the properties that only have data
  19.             if($user.($singleproperty).GetType().Name -eq "ADPropertyValueCollection") { #if it is a property value collection
  20.                 foreach ($collectionitem in $user.($singleproperty)) { #foreach item in the collection
  21.                     if ($collectionitem.Contains("@")) { #if it contains a whir
  22.                         $results += New-Object -TypeName PSObject -Property @{"samaccountname"=$user.SamAccountName;"emailaddress"=$collectionitem.ToLower().Replace("smtp:","").Replace("sip:","")}
  23.                     } #if it contains a whirl
  24.                 } #foreachitem in the collection
  25.             } else {
  26.                 if ($user.($singleproperty).Contains("@")) { #if it contains a whir
  27.                     $results += New-Object -TypeName PSObject -Property @{"samaccountname"=$user.SamAccountName;"emailaddress"=$user.($singleproperty).ToLower().Replace("smtp:","").Replace("sip:","")}
  28.                 } #if it contains a whirl
  29.             } #if else collection or string
  30.         } #if the property has datea
  31.     } #foreach property
  32. } #foreach user
  33. $results = $results | Sort-Object -Property emailaddress | Get-Unique -AsString
  34. $results
Advertisement
Add Comment
Please, Sign In to add comment