1

I am building a PowerShell script to loop through all site collections and their sub-sites to get all users who are defined inside the related site owner group. Currently, I have this script where I need to provide each site collection URL manually, as follow:-

<#
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.SYNOPSIS
  Name: Get-FullOwnerReport.ps1
  This script looks for and reports all users and groups that have full control access for all sites and subsites
  in a user's tenant

.Requirements
SPO PnP Module: https://github.com/SharePoint/PnP-PowerShell/releases 

.PARAMETER rootSite
  The SharePoint Online root site url

.PARAMETER outputPath
  The file path that the user wishes to contain the final report


.OUTPUTS
Exports data into a csv named FullOwnersReport.csv

  
.EXAMPLE
  .\Get-FullOwnerReport.ps1 -rootSite "https://myTenant.sharepoint.com" -outputPath "c:\temp"

#>

param(
    [Parameter(Mandatory=$true,
    HelpMessage="Enter sharepoint root url",
    ValueFromPipeline=$false)]
    $rootSite,

    [Parameter(Mandatory=$true,
    HelpMessage="Enter file path to create CSV report in",
    ValueFromPipeline=$false)]
    [ValidateScript({ Test-Path $_ -PathType Container  })]
    $outputPath
)

try
{
    Import-Module SharePointPnPPowerShellOnline -ErrorAction Stop
}
catch
{
    Start-Process -FilePath "powershell" -Verb runas -ArgumentList "Install-Module SharePointPnPPowerShellOnline -Force -AllowClobber;" -Wait
    Import-Module SharePointPnPPowerShellOnline
}

$spcred = Get-Credential

$allSubSites = @()
$urls = @()
$allGroupSites = @()

Connect-PNPonline -Url "$($rootSite)"  -UseWebLogin
$urls = Get-PnPTenantSite -Url "$rootSite"  -IncludeOneDriveSites  -Detailed

foreach($url in $urls)
{
    try
    {
       Connect-PNPonline -Url "$($url.Url)"  -ErrorAction SilentlyContinue -UseWebLogin
        $allSubSites += Get-PnPSubWebs -Recurse -ErrorAction SilentlyContinue
    }
    catch
    {
        Write-Warning -Message "Warning Access to $($url.Url) was denied."
    }
}

$allSubSites += $urls
$allOwners = @()
foreach($url in $allSubSites)
{
    try
    {
        Connect-PNPonline -Url "$($url.Url)"  -ErrorAction Stop -UseWebLogin
        $owners = Get-PnPGroup -ErrorAction Stop | where {$_.Title -match "Owners"} 
        foreach($owner in $owners)
        {

            $allOwnerGroups  = Get-PnPGroupMembers -Identity "$($owner.Title)"
            Write-Host "Accessing users of group $($owner.Title)"

            foreach($lowerOwner in $allOwnerGroups)
            {
                Write-Host "User $($lowerOwner.LoginName) found as owner for site $($url.Url)"

                $object = New-Object –TypeName PSObject
                $object | Add-Member –MemberType NoteProperty –Name LoginName –Value $lowerOwner.LoginName
                $object | Add-Member –MemberType NoteProperty –Name Email –Value $lowerOwner.Email
                $object | Add-Member –MemberType NoteProperty –Name URL –Value "$($url.Url)"

                $allOwners += $object
            }
        }
    }
    catch
    {
        Write-Warning -Message "Warning Access to $($url.Url) was denied."
    }

}

$GroupReport = $outputPath + "\FullOwnersReport.csv"

if((Test-Path -Path "$GroupReport"))
{
    $allOwners  | Export-Csv -Path "$GroupReport" -Force -NoTypeInformation
}
else
{
    New-Item -Path "$GroupReport" -ItemType file
    $allOwners  | Export-Csv -Path "$GroupReport" -Force -NoTypeInformation
}

Can I modify the script to automatically loop through all the site collections inside our tenant and their sub-sites for getting the users inside the Site Owner group?

2 Answers 2

0

Try to execute the below PowerShell which will fetch the Site Collections from the tenant by providing the tenant URL.

# Input Parameters     
$spcred = Get-Credential   
$URL = "Tenant URL"  
    
# Connect to SharePoint Online   
Connect-PnPOnline -Url $URL -UseWebLogin
  
# Get the site collections  
$siteColl = Get-PnPTenantSite  
  
# Loop through the site collections  
$allSubSites = @()
foreach($site in $siteColl)  
{  
    write-host -ForegroundColor Green "Site Collection: " $site.Url  
    Connect-PnPOnline -Url $site.Url -UseWebLogin
  
    $allSubSites += Get-PnPSubWebs -Recurse -ErrorAction SilentlyContinue
}  

After fetching the sub-sites, try to execute your script for getting the users from the Site Owner group.

0

Please run the below PowerShell script:

Install-Module -Name SharePointPnPPowerShellOnline

#Provide your SharePoint Online Admin center URL
$AdminSiteURL = "https://<Tenant_Name>-admin.sharepoint.com"
 
#Get SharePoint Admin User Credentials  
$Cred = Get-Credential
 
#Connect to SharePoint Admin Site
Connect-PnPOnline -Url $AdminSiteURL -Credentials $Cred 
 
#Get all site collections
$Sites = Get-PnPTenantSite
#The below command gets only modern Team & Communication sites
#$Sites = Get-PnPTenantSite | Where -Property Template -In ("GROUP#0", "SITEPAGEPUBLISHING#0")
   
$AllSites = @()
 
$i = 0;
$TotoalSites = $Sites.Count

#Enumerate site collections and get sub sites recursively
ForEach($Site in $Sites)
{
    $i++;
    Write-Progress -activity "Processing $($Site.Url)" -status "$i out of $TotoalSites completed"
 
    $SubWebs=$null;
    Try
    {
    
        #Connect to site collection
        $SiteConnection = Connect-PnPOnline -Url $Site.Url -Credentials $Cred
   
        #Get the sub sites of the site collection
        $SubWebs = Get-PnPSubWeb -Recurse -Connection $SiteConnection
  
        Disconnect-PnPOnline -Connection $SiteConnection
    }
    catch{
        Write-Host "Error occured $($Site.Url) : $_.Exception.Message"   -Foreground Red;
    }
 
    #Add site collection in AllSites list 
    $AllSites += New-Object PSObject -property $([ordered]@{ 
        SiteName  = $Site.Title            
        SiteURL = $Site.Url
        IsSubSite = $false
        HasSubSites = if ($SubWebs -and $SubWebs.Count -gt 0) { $true } Else {$false}
        SiteCollectionName = $Site.Title
        SiteCollectionURL = $Site.Url
    })
 
    if ($SubWebs -and $SubWebs.Count -gt 0) {
    
        #Enumerate sub sites and add in AllSites list 
        ForEach($SubSite in $SubWebs)
        {
            $AllSites += New-Object PSObject -property $([ordered]@{ 
            SiteName  = $SubSite.Title            
            SiteURL = $SubSite.Url
            IsSubSite = $true
            HasSubSites = $false
            SiteCollectionName = $Site.Title
            SiteCollectionURL = $Site.Url
            })
        }
    }
}

#Display all site collections and sub sites
$AllSites | Select SiteName,SiteURL,IsSubSite
#$AllSites | Export-CSV "C:\AllSites-and-SubSites.CSV" -NoTypeInformation -Encoding UTF8
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.