Get SharePoint Users and Groups Info

This script uses the SharePoint commands to gather all the users and groups with access to your Central Administration SP site.
It mails the report using SMTP and it will upload the report to a SharePoint site.
This script must be run as a Farm Administrator to get complete results.

It puts it out in a HTML format. It is usefull for those security audits that come up from time to time.
The is adapted from the code I found here which puts out the results in a quasi XML format.
:

#Function to send out email 
function sendMail($emailTo,$outFile) 
{ 
    $smtpServer = "smtp.org" #<-- Your SMTP mail server
    $emailFrom = "$machineName@yourdomain.com"  
    $subject = "$MachineName SharePoint Users Info - $date" 
    $body = "See Attached."  
	
	If ($outFile -eq $null) {
		# no attachement
		$body += $Results
        Send-MailMessage -From $emailFrom -To $emailTo -Subject $subject  -Body $body -SmtpServer $smtpServer 
	}
	Else
	{
		# with $outfile as attachement
        Send-MailMessage -From $emailFrom -To $emailTo -Subject $subject  -Body $body -Attachments $outFile -SmtpServer $smtpServer
    }
} 

function DisplayWeb #-web SPWeb -depth int -parentWeb SPWeb
{
   if($args[0].HasUniquePerm -eq "True")
  {
    $UserAccess = DetermineUserAccess $args[0] ($args[1] + 1)
  }
  

  if($args[0].Webs -ne $Null)
  {
    # RECURSIVELY SEARCH SUBWEBS
    foreach ($spSubWeb in $args[0].Webs)
    {
      $subWeb = DisplayWeb $spSubWeb ($args[1] + 2)
      $spSubWeb.Dispose()
    }
    # END CONTAINED SUBSITES ENTITY
   
  }

  # END SITE ENTITY
  Return $subWeb
}

function DisplayMissingParametersMessage
{
  #Write-Output "You are missing a parameter for 'Site URL'"
  $script:siteURL = Read-Host "Enter Site URL"
}
<#
This report must be run as a Farm Administrator to get complete results.
The report will mail itself to a person or group and upload the report file to a 
SharePoint site. ("http://sharepoint/Shared%20Documents")
:: Usage:
.\SP Security Report.ps1' "http://ServerName:51234" <-- Change the server name as appropriate.


#>
############
# MAIN
############

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#IF MISSING PARM FOR SITE URL, ASK FOR INPUT TO FILL
if($args.length -eq 0)
{
  DisplayMissingParametersMessage
}

[string]$siteUrl = $args[0]
[string]$searchScope = $args[1]
[string]$userToFind = $args[2]

#Import-module active*
$server = $env:computername
$date = ( get-date ).ToString('MM-dd-yyyy')
$MachineName = $env:COMPUTERNAME
$u = @()
$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)
$spWebApp = $rootSite.WebApplication

#IF SEARCH SCOPE SPECIFIED FOR SITE, ONLY SEARCH SITE
if($searchScope -eq "-site")
{
  DisplaySiteCollection $rootSite 1
}
#ELSE SEARCH ENTIRE WEB APP
else
{
  #DisplayWebApplication $spWebApp 1
}

# Create Webpage Header
$z = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`"  `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$z = $z + "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$z = "<head><style>"
$z = $z + "TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}"
$z = $z + "TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}"
$z = $z + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}"
$z = $z + "</style></head><body>"
$z = $z + "<H4>SharePoint Users Report for $env:COMPUTERNAME Central Admin $date</H4>"
$z = $z + "<table><colgroup><col/><col/><col/><col/><col/><col/><col/></colgroup>"
$z = $z + "<tr><th>Web App</th><th>Web</th><th>Site Collection</th><th>Site User</th><th>SPGroup</th><th>SPGroupMembers</th><th>Local Group</th></tr>"
$MainWebApp = $spWebApp
$MainDisplayWeb = DisplayWeb 
$subSite = @()

ForEach ($site in $SpWebApp){
$MainSiteCollection = @()
$a = $site.Sites 
	forEach ($a1 in $a) {
	$sSite = $a1.ToString().split("=")
		$SubSite = $subSite + $sSite[1]
	$MainSiteCollection = "$MainSiteCollection $sSite <br>"
	}
}

$z = $z + "<tr><td>$MainWebApp</td><td>$MainDisplayWeb</td><td>$MainSiteCollection</td><td></td></tr>"

ForEach ($site in $SubSite){
$siteUser = @()
$u1 = @()
$SPGroups = @()
$MainSPGroupMembers = @()
$rSite = New-Object Microsoft.SharePoint.SPSite($site)
$x = $rSite.rootweb
$x1 = $x.users

ForEach ($i in $x1) { 
$u = $i.UserLogin
$u2 = $u.ToString().split(".")
$u1 = "$u1  $u2 <br>"
$siteUser = "$u1<br>"
 }
foreach($group in $rsite.RootWeb.SiteGroups)
{	
    $b = $group.Name 
    $sGroup = $b.ToString().split(".")
	$SPGroup = $sGroup[0]
	$SPGroups = ($SPGroup)
	$LocalGrp = @()
	$lgn = @()
	$lgm = @()
	$MemberName = @()
	$x1 = @()
	$x = $null
	foreach ($user in $group.Users)
    {    
		$D = $user.UserLogin
			$D1 = $D.ToString().split(".")
			$D2 = $D.ToString().split("\")
			$SPGroupMembers = "$D1"
			$MainSPGroupMembers = ("$MainSPGroupMembers $SPGroupMembers <br>")
		If ($User.IsDomainGroup) {
			$x = $user
			$lgn = $x
			$x1 = $x1 + $x 
			forEach ($x2 in $x1) {
			$Lgm = $Null
			$y = $Null
			$gName = $x2.ToString().split("\")
			$groupName = $gName[1]
			  #BEGIN - CODE ADAPTED FROM SCRIPT CENTER SAMPLE CODE REPOSITORY
			  #http://www.microsoft.com/technet/scriptcenter/scripts/powershell/search/users/srch106.mspx
			  #GET AD GROUP FROM DIRECTORY SERVICES SEARCH
			  $strFilter = "(&(objectCategory=Group)(name="+($groupName)+"))"
			  $objDomain = New-Object System.DirectoryServices.DirectoryEntry
			  $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
			  $objSearcher.SearchRoot = $objDomain
			  $objSearcher.Filter = $strFilter
				$colProplist = ("name","member")
				foreach ($i in $colPropList)
					{
					$catcher = $objSearcher.PropertiesToLoad.Add($i)
					}
						$colResults = $objSearcher.FindAll()

				#END - CODE ADAPTED FROM SCRIPT CENTER SAMPLE CODE REPOSITORY
				  foreach ($objResult in $colResults)
				  {
					foreach ($member in $objResult.Properties.member)
					{
					  $indMember = [adsi] "LDAP://$member"
					    $y = $domain + ($indMember.Name) 
						$Lgm = ("$Lgm <tr><td>$y</td></tr>")
						}
					 }
			}	
			$LocalGrp = ("$LocalGrp <TABLE><td><strong>$lgn</strong></td><td>$Lgm</td></tr></TABLE>")
			}
	}
	$lgnlgm = $Localgrp
	$z = $z + "<tr><td></td><td>$site</td><td></td><td>$siteUser</td><td>$SPGroups</td><td>$MainSPGroupMembers</td><td>$lgnlgm</td><tr>"
	}
	$rSite.Dispose()
}

# Create Table
$surl = $siteUrl.ToString().split("/")
$s = "CA"
# $s = $surl[2]
# $s = ($s -replace ":", "-") 
$MainWebApp = $spWebApp
$MainDisplayWeb = DisplayWeb
$z = $z + "</table></body></html>"

# Adjust Path
$OutFileName = ("G:\Reports\" + $server + "-" + $s + "-SharePoint Security Report-" + $date + ".html")
#
Out-File -FilePath $OutFileName -InputObject $z -Encoding ASCII	
#End Table
$OutFileItem = Get-Item -Path $OutFileName
Write-Host " Report available here: $OutFileItem" -Foregroundcolor Yellow
sendMail user@yourmai.com $OutFileItem #<--- Change email address

# upload the report to a SharePoint site
$userName = Read-Host "Enter your username"
$password = Read-Host "Enter your password"
 
 $path = "G:\Reports"; #<--- Change directory
 $destination = "http://sharepoint/Shared Documents"; 
 $securePasssword = ConvertTo-SecureString $password -AsPlainText -Force;
 $credentials = New-Object System.Management.Automation.PSCredential ($userName, $securePasssword);
 #$credentials = [System.Net.CredentialCache]::DefaultCredentials; 
 $webclient = New-Object System.Net.WebClient;
 $webclient.Credentials = $credentials; 
 Get-ChildItem $path | Where-Object {$_.Extension -eq ".html"} | 
 ForEach-Object { $webclient.UploadFile($destination + "/" + $_.Name, "PUT", $_.FullName); 
 }
#CLEANUP
$rootSite.Dispose()

Advertisements

2 thoughts on “Get SharePoint Users and Groups Info

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s