Thursday, November 1, 2012

Get all SharePoint Users and Groups using PowerShell Script



# it shows username, emailid, group names which user belogns to 
# domainname\surya, surya@xyz.com, group1; group2; group3;

copy below code to notepad file and save it as "users_groups.ps1" file.
Run the below script using SharePoint management shell. once you run the script you can see the .csv file will be created where you are running this file. for ex: if you are running this script d:\surya, you can the log file in the same location.


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$site = New-Object Microsoft.SharePoint.SPSite("http://spdev6:8003")
$web = $site.openweb("")
 Write-Host $web.url
     
           
$i = 1
#logging
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "UsersLog"
$logfile = ("{0}{1}.txt" -f $filenamestart, $timestamp)

$header = "UserName,Email, Group"
$header | out-file -FilePath $logfile

      write-host $i   "UserName:"  $user  "Groups:" $user.groups

            #Write-Host "siteusers" $web.siteusers["ajay.thomas"]
      $semicolon = ";" 
     
      Write-Host $semicolon
      foreach ($user in $web.siteusers)
      {
     
      #[string]$UserName= $user.ToString()
      #if ($UserName.ToUpper().StartsWith("surya"))
      #{
     
     
            foreach ($grp in $user.groups)
            {
                  $str = $str +  $grp.name + $semicolon
                  #Write-host   $grp.name  ";"
            }
            #Write-Host $i  $user  "," $user.email  ","   $str
            Write-Host $user  "," $user.email ","  $str "," $user.ID
# $user.group
           
            $msg = ("{0},{1},{2} " -f $user, $user.email, $str)
            $msg | out-file -FilePath $logfile  -append
     
     
     
            $str= $null
      #}   
 
       
       #Write-Host $i++
  }
 
 
     
 
$site.Dispose()



Followers