Hello Readers,

This article as the name states will be a PowerShell script to get the email ids of the all the users present in a site and its sub sites. We get this requirement for the migration purpose and also when our clients need the email ids of all the users in their site to send email to.

This script will help you to save us developers a lot of time. Initially I thought I will save my effort by searching for the script but didn’t have one so thought of writing it for my fellow developers too.

So here is the script let’s see it here.

  1. Copy the code below to a .ps1 file.

  2. Create a new text file named anything.

  3. Add a heading in that text file as Webs, underline you can paste as many url of the sites as you want their email ids of all the users.

  4. Change the location of the file in the script.

  5. Run the .ps1 file

  6. You will receive the resulted file in a text file named as AllUserEmails.

Script

  1. #get all users from Site level
  2. #Snapin
  3. Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
  4. #File Output Name Generator
  5. $filenameStart = "AllUserEmails"
  6. $logfile = ("{0}.xml" -f $filenamestart)
  7. out-file -FilePath $logfile
  8. $userDetailsArray = @()
  9. $finaluserDetailsArray = @()
  10. #Calling the list and Connecting the site
  11. $Webst = @()
  12. $userobjects = Import-Csv “Text file with Sites Location here”
  13. Write-Host $userobjects
  14. foreach($userobject in $userobjects)
  15. {
  16. $site = new-object Microsoft.SharePoint.SPSite($userobject.Webs)
  17. Write-Host $userobject.Webs -foregroundcolor green
  18. foreach($sites in $site)
  19. {
  20. Write-Host $site -foregroundcolor blue
  21. $web = $site.openweb()
  22. Write-Host $web -foregroundcolor blue
  23. $siteUsers = $web.SiteUsers
  24. Write-Host $subs -foregroundcolor white
  25. foreach ($userw in $siteUsers)
  26. {
  27. if ($userw -like "Domain\*")
  28. {
  29. write-host " " $userw -foregroundcolor white
  30. $userwLogin = $userw.LoginName
  31. $userDetailsArray =$userDetailsArray + $userwLogin
  32. }
  33. }
  34. $web.Dispose()
  35. }
  36. }
  37. #Tagging them to an array
  38. $userArray = $userDetailsArray | select -unique
  39. foreach ($value in $userArray)
  40. {
  41. $valueemail = $value.Split("\")
  42. $emailval = $valueemail[1]
  43. #Result to txt File
  44. "$emailval"+"@gmail.com"+";" | out-file -FilePath $logfile -append
  45. }

Keep Leaning.

Cheers !!