Date and Month display

Full Control users report on SharePoint online site collection as well as Unique Sub Sites across Tenant Level

<#
******-----------------------------------------------------------------------******
Author          -> Shiv Mangal Singh
Date            -> 16 th August - 2017
Description     -> This Script will generate Members of the owners group, member of other groups with full control, and direct full control permissions User's List
                    Entire SharePoint online site collection as well as Unique Sub Sites across Tenant Level
                ->

Path of csv file --> $FileUrl ="D:\shiv\Powershell\OnlineSites_16August20117.csv"
                 --> $currentLogPath ="D:\shiv\Powershell\Onlinelog_16August2017.csv"
Tenant Site URL  --> $AdminURL = "https://office365.connect.contoso"

******-----------------------------------------------------------------------******
 #>
#Import-Module ‘C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell’ -DisableNameChecking

Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path 'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.Client.Tenant.dll'
Add-Type -Path "D:\shiv\Powershell\DLL\Microsoft.SharePoint.Client.UserProfiles.dll"

#Required Parameters
$AdminURL = "https://office365.connect.contoso"
$sUsername = "MS@contoso.onmicrosoft.com"
$sPassword = Read-Host -Prompt "Enter your password: " -AsSecureString  
#Connect-SPOService -Url $AdminURL -Credential $

#Connect to SharePoint Online
  #SPO Client Object Model Context
        $spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($AdminURL)
        $spoCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sUsername, $sPassword)  
        $spoCtx.Credentials = $spoCredentials
        $spoTenant= New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($spoCtx)
        $spoTenantSiteCollections=$spoTenant.GetSiteProperties(0,$true)
        $spoCtx.Load($spoTenantSiteCollections)
        $spoCtx.ExecuteQuery()
# File Directory for reports and logs
$FileUrl ="D:\shiv\Powershell\OnlineSites_16August20117.csv"
$currentLogPath ="D:\shiv\Powershell\Onlinelog_16August2017.csv"
# Headers for the data
“Site URL `t Group Name `t Permission `t Email `t User” | Out-File $FileUrl

#Logs and prints messages
function LogMessage([String] $Msg)
{
    Write-Host $Msg -ForegroundColor Cyan
    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") Message: $Msg" | Out-File -FilePath $currentLogPath -Append -Force
}
#Logs and prints error messages
function LogError([String] $ErrorMessage, [String]$ErrorDetails, [String]$ErrorPosition)
{
    Write-Host $ErrorMessage -foregroundcolor red
    $fullErrorMessage = $ErrorMessage + $ErrorDetails + ". " + $ErrorPosition
    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") ERROR: $fullErrorMessage" | Out-File -FilePath $currentLogPath -Append -Force
}

Function Invoke-LoadMethod()
 {
param(
   [Microsoft.SharePoint.Client.ClientObject]$Object = $(throw "Please provide a Client Object"),
   [string]$PropertyName
)
   $ctx = $Object.Context
   $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
   $type = $Object.GetType()
   $clientLoad = $load.MakeGenericMethod($type)


   $Parameter = [System.Linq.Expressions.Expression]::Parameter(($type), $type.Name)
   $Expression = [System.Linq.Expressions.Expression]::Lambda(
            [System.Linq.Expressions.Expression]::Convert(
                [System.Linq.Expressions.Expression]::PropertyOrField($Parameter,$PropertyName),
                [System.Object]
            ),
            $($Parameter)
   )
   $ExpressionArray = [System.Array]::CreateInstance($Expression.GetType(), 1)
   $ExpressionArray.SetValue($Expression, 0)
   $clientLoad.Invoke($ctx,@($Object,$ExpressionArray))
}

#Get all Sites (Root sites only)
foreach($site in $spoTenantSiteCollections)
{
   try
   {
 # Skip Mydrive site from Report
if($site.Url -ne "https://mydrive.abc.contoso/")
#if($site.Url -like "*Migra*")
{
Write-Host $site.Url "Connected !" -foregroundcolor black -backgroundcolor Green
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($site.Url)
$ctx.Credentials =   $spoCredentials
$rootsite= $ctx.Web
$ctx.Load($rootsite)
$spWebs =$rootsite.Webs
$ctx.Load($spWebs)
$ctx.ExecuteQuery()

#*********function To get Full control/ Owner/ Direct Full control permission
function GetSitesOwners($web)
{
 $ctx.Load($web.RoleAssignments)
 $ctx.ExecuteQuery()
   # Check Owners group
   $GroupSiteOwneruser = @()
   $SiteGroup =$web.SiteGroups
   $ctx.Load($SiteGroup)
   $ctx.ExecuteQuery()
  # Get direct/explicit  users permission from site collection
     $WebRoleAssignments = $web.RoleAssignments
     $ctx.Load($WebRoleAssignments)
     $ctx.ExecuteQuery()
     foreach($WebRoleAssignment in $WebRoleAssignments)
        {
         $ctx.Load($WebRoleAssignment.Member)
         $ctx.Load($WebRoleAssignment.RoleDefinitionBindings)
         $ctx.ExecuteQuery()
        if($WebRoleAssignment.Member.PrincipalType -eq [Microsoft.SharePoint.Client.Utilities.PrincipalType]::User)  
            {
            #Get the Permissions assigned to user
             $WebUserPermissions=@()
              foreach ($RoleDefinition  in $WebRoleAssignment.RoleDefinitionBindings)
               {
                $ctx.Load($RoleDefinition)
                $ctx.ExecuteQuery()
                if($RoleDefinition.Name -like "*Full*")
                  {
                  $WebUserPermissions += $RoleDefinition.Name +";"
                  }
                }
                if($WebUserPermissions)
                     {
                     "$($web.Url) `t Direct Permission `t $($WebUserPermissions)`t $(($WebRoleAssignment.Member.LoginName).split('|')[2]) `t $(($WebRoleAssignment.Member.LoginName).split('|')[2]) " | Out-File $FileUrl -Append
                     }
              }
        }
      # Ended loop direct users permission list from site
 
   #Get users permission list from Sharepoint group
             foreach($grpUser in $SiteGroup)
              {
              try
              {
               $ctx.Load($grpUser)
               $ctx.ExecuteQuery()
                $siteuser = $grpUser.Users
                $ctx.Load($siteuser)
                $ctx.ExecuteQuery()
             
                  $grpWebRoleAssignment = $web.RoleAssignments.GetByPrincipal($grpUser)
                  foreach($WebRoleAssignment in $grpWebRoleAssignment)
                    {
                    $ctx.Load($WebRoleAssignment)
                    $RoleDefinitions =$WebRoleAssignment.RoleDefinitionBindings
                    $ctx.Load($RoleDefinitions)
                    $ctx.ExecuteQuery()
                    $WebUserPermissions=@()
                    foreach ($RoleDefinition  in $RoleDefinitions)
                     {
                     #Excldue "Limited Access" users permission
                     if($RoleDefinition.Name -like "*Full*")
                      {
                      $WebUserPermissions += $RoleDefinition.Name +";"
                      }
                     }
                     # Iterate users
                     $FullControlOwner =@()
                     $EmailOwner=@()
                     foreach($user in $siteuser)
                       {
                       $ctx.Load($user)
                       $ctx.ExecuteQuery()
                       $FullControlOwner +=$user.Title + ";"
                       if($user.Title -like "*SVC*")
                       {
                       $EmailOwner +=($user.LoginName).split('|')[2] + ";"
                      # Write-Host $user.LoginName  -ForegroundColor Yellow
                       }
                       else
                       {
                       $EmailOwner +=$user.Email+ ";"
                       }
                     }
                     if($WebUserPermissions)
                     {
                         "$($web.Url) `t $($grpUser.Title) `t $($WebUserPermissions) `t $($EmailOwner) `t $($FullControlOwner) " | Out-File $FileUrl -Append
                     }
                   }      
          }

        catch [System.Exception]
            {
            $Errormessage =$_.Exception.Message
               Write-Host "Can not find the user in this SharePoint group ID" "[$Errormessage]" -ForegroundColor Cyan
            }

 }

}  
#************ending function to get Full control/ Owner/ Direct Full control permission

GetSitesOwners($rootsite)
 #********************** checking for sub sites***************************************#
 # $spWebs for all sub sites

   foreach($subsite in $spWebs)
   {
   # Invoke-LoadMethod is a function to get unique sub site details
   Invoke-LoadMethod -Object $subsite -PropertyName "HasUniqueRoleAssignments"
   $ctx.Load($subsite)
   $ctx.Load($subsite.Webs)
   $ctx.ExecuteQuery()
   if($subsite.HasUniqueRoleAssignments -eq $true)
   {
   GetSitesOwners($subsite)
   }
   # checked one level of sub sites
   foreach($Subsiteonelevel in $subsite.Webs)
   {
    try
     {
     Invoke-LoadMethod -Object $Subsiteonelevel -PropertyName "HasUniqueRoleAssignments"
     $ctx.Load($Subsiteonelevel)
     $ctx.ExecuteQuery()
         if($Subsiteonelevel.HasUniqueRoleAssignments -eq $true)
         {
         GetInnerSubsite($Subsiteonelevel)
         }
      }
          catch
          {
           if($_.Exception.Message -like '*(401) Unauthorized*' -or $_.Exception.Message -like '*Access denied*')
             {
              LogMessage("You need permission to access this site: "+ $Subsiteonelevel.Url)
             }
             else
              {
                LogError $_.Exception.Message $_.Exception.GetType().FullName $_.InvocationInfo.PositionMessage
              }
           }
 
   }  # closing one level of sub sites
  }


 #**************Recrusive Sub Sites **********************************************************#
  function GetInnerSubsite($subWeb)
        {
          try
          {
         Invoke-LoadMethod -Object $subWeb -PropertyName "HasUniqueRoleAssignments"
         $ctx.Load($subWeb)
         $ctx.Load($subWeb.Webs)
         $ctx.ExecuteQuery()

         if($subWeb.HasUniqueRoleAssignments -eq $true)
          {
          GetSitesOwners($subWeb)
          }
         }
          catch
          {
           if($_.Exception.Message -like '*(401) Unauthorized*' -or $_.Exception.Message -like '*Access denied*')
             {
              LogMessage("You need permission to access this site: "+ $subWeb.Url)
             }
             else
              {
                LogError $_.Exception.Message $_.Exception.GetType().FullName $_.InvocationInfo.PositionMessage
              }
           }
        foreach($subsubinnersite in $subWeb.Webs)
            {
            try
            {
             Invoke-LoadMethod -Object $subsubinnersite -PropertyName "HasUniqueRoleAssignments"
             $ctx.Load($subsubinnersite)
             $ctx.ExecuteQuery()
             if($subsubinnersite.HasUniqueRoleAssignments -eq $true)
              {
              GetInnerSubsite($subsubinnersite)
              }
             }
              catch
              {
               if($_.Exception.Message -like '*(401) Unauthorized*' -or $_.Exception.Message -like '*Access denied*')
                 {
                  LogMessage("You need permission to access this site: "+ $subsubinnersite.Url)
                 }
                 else
                  {
                    LogError $_.Exception.Message $_.Exception.GetType().FullName $_.InvocationInfo.PositionMessage
                  }
               }

            }

        }

 #********************End of Recrusive Sub Sites***********************************************#

 }

 }
 catch
 {
 if($_.Exception.Message -like '*(401) Unauthorized*' -or $_.Exception.Message -like '*Access denied*')
                 {
                  LogMessage("You need permission to access this site: "+ $site.Url)
                 }
                 else
                  {
                    LogError $_.Exception.Message $_.Exception.GetType().FullName $_.InvocationInfo.PositionMessage
                  }
 }
 }

<#***    The END (Users Permission list across Tenant level)  #>

No comments:

Post a Comment