PowerShell Script to get the Email iDs of all the Users Present on a Site and its Sub Sites

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.   
  8. out-file -FilePath $logfile  
  9.     $userDetailsArray = @()  
  10.     $finaluserDetailsArray = @()  
  11. #Calling the list and Connecting the site  
  12. $Webst = @()  
  13. $userobjects = Import-Csv “Text file with Sites Location here”  
  14. Write-Host $userobjects  
  15. foreach($userobject in $userobjects)  
  16. {  
  17.    $site = new-object Microsoft.SharePoint.SPSite($userobject.Webs)  
  18.    Write-Host $userobject.Webs -foregroundcolor green  
  19.    foreach($sites in $site)  
  20.    {  
  21.       Write-Host $site -foregroundcolor blue  
  22.       $web = $site.openweb()                  
  23.       Write-Host $web -foregroundcolor blue  
  24.       $siteUsers = $web.SiteUsers  
  25.       Write-Host $subs -foregroundcolor white  
  26.       foreach ($userw in $siteUsers)  
  27.       {  
  28.       if ($userw -like "Domain\*")  
  29.       {  
  30.          write-host "        " $userw -foregroundcolor white                      
  31.          $userwLogin = $userw.LoginName  
  32.              $userDetailsArray =$userDetailsArray + $userwLogin           
  33.       }  
  34.       }  
  35.       $web.Dispose()  
  36.    }  
  37. }  
  38. #Tagging them to an array  
  39. $userArray = $userDetailsArray | select -unique   
  40. foreach ($value in $userArray)   
  41. {  
  42.     $valueemail = $value.Split("\")  
  43.     $emailval = $valueemail[1]     
  44.     #Result to txt File     
  45.    "$emailval"+"@gmail.com"+";" | out-file -FilePath $logfile  -append      
  46. }  

Keep Leaning.

Cheers !!