I'm trying to create a PowerShell script to generate a report of user permissions (members and admins) across all SharePoint Online sites in my tenant.
My primary goal is to identify which SharePoint sites are relevant to a subset of users so we can determine which sites need to be migrated to a new tenant.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll help you create a PowerShell script to generate a comprehensive report of user permissions across all SharePoint Online sites. This script will identify site members and admins, which will help you determine which sites are relevant for specific users during your migration planning.
Here's a PowerShell script that accomplishes this:
powershell
# SharePoint Online User Permissions Report Script
# This script generates a CSV report of all users and their permissions across all SPO sites
# Parameters
param(
[Parameter(Mandatory=$false)]
[string]$OutputPath = ".\SPO_Permissions_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv",
[Parameter(Mandatory=$false)]
[string[]]$TargetUsers = @(), # Array of user emails to specifically track
[Parameter(Mandatory=$false)]
[switch]$IncludeOneDrivesSites = $false
)
# Connect to SharePoint Online
function Connect-SPOService {
$adminUrl = Read-Host "Enter your SharePoint Admin Center URL (e.g., https://contoso-admin.sharepoint.com)"
try {
Connect-SPOService -Url $adminUrl
Write-Host "Successfully connected to SharePoint Online" -ForegroundColor Green
}
catch {
Write-Host "Failed to connect to SharePoint Online: $_" -ForegroundColor Red
exit
}
}
# Get all site collections
function Get-AllSiteCollections {
Write-Host "Retrieving all site collections..." -ForegroundColor Yellow
try {
$sites = Get-SPOSite -Limit All
if (-not $IncludeOneDrivesSites) {
$sites = $sites | Where-Object { $_.Url -notlike "*/personal/*" }
}
Write-Host "Found $($sites.Count) site collections" -ForegroundColor Green
return $sites
}
catch {
Write-Host "Error retrieving sites: $_" -ForegroundColor Red
return @()
}
}
# Get permissions for a specific site
function Get-SitePermissions {
param(
[Parameter(Mandatory=$true)]
$Site
)
$permissions = @()
try {
# Get site admins
$siteAdmins = Get-SPOUser -Site $Site.Url -Limit All | Where-Object { $_.IsSiteAdmin -eq $true }
foreach ($admin in $siteAdmins) {
$permissions += [PSCustomObject]@{
SiteUrl = $Site.Url
SiteTitle = $Site.Title
UserEmail = $admin.LoginName
DisplayName = $admin.DisplayName
PermissionLevel = "Site Collection Administrator"
UserType = $admin.UserType
IsTargetUser = if ($TargetUsers -contains $admin.LoginName) { "Yes" } else { "No" }
}
}
# Get site members (non-admins)
$siteMembers = Get-SPOUser -Site $Site.Url -Limit All | Where-Object { $_.IsSiteAdmin -eq $false }
foreach ($member in $siteMembers) {
# Skip system accounts and app principals
if ($member.LoginName -notlike "*#ext#*" -and
$member.LoginName -notlike "app@*" -and
$member.LoginName -notlike "SHAREPOINT\*" -and
$member.LoginName -notlike "c:0*") {
$permissions += [PSCustomObject]@{
SiteUrl = $Site.Url
SiteTitle = $Site.Title
UserEmail = $member.LoginName
DisplayName = $member.DisplayName
PermissionLevel = "Site Member"
UserType = $member.UserType
IsTargetUser = if ($TargetUsers -contains $member.LoginName) { "Yes" } else { "No" }
}
}
}
}
catch {
Write-Host "Error processing site $($Site.Url): $_" -ForegroundColor Red
}
return $permissions
}
# Main execution
function Start-PermissionsReport {
Write-Host "`nStarting SharePoint Online Permissions Report Generation" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
# Connect to SPO
Connect-SPOService
# Get all sites
$allSites = Get-AllSiteCollections
if ($allSites.Count -eq 0) {
Write-Host "No sites found to process" -ForegroundColor Yellow
return
}
# Process each site
$allPermissions = @()
$processedCount = 0
foreach ($site in $allSites) {
$processedCount++
Write-Progress -Activity "Processing SharePoint Sites" -Status "Processing $($site.Url)" -PercentComplete (($processedCount / $allSites.Count) * 100)
Write-Host "Processing site $processedCount of $($allSites.Count): $($site.Url)" -ForegroundColor Gray
$sitePermissions = Get-SitePermissions -Site $site
$allPermissions += $sitePermissions
}
Write-Progress -Activity "Processing SharePoint Sites" -Completed
# Export results
if ($allPermissions.Count -gt 0) {
$allPermissions | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Host "`nReport generated successfully!" -ForegroundColor Green
Write-Host "Total permissions found: $($allPermissions.Count)" -ForegroundColor Green
Write-Host "Report saved to: $OutputPath" -ForegroundColor Green
# If target users were specified, show summary
if ($TargetUsers.Count -gt 0) {
Write-Host "`nTarget User Summary:" -ForegroundColor Cyan
$targetUserPermissions = $allPermissions | Where-Object { $_.IsTargetUser -eq "Yes" }
$targetSites = $targetUserPermissions | Select-Object -ExpandProperty SiteUrl -Unique
Write-Host "Target users found in $($targetSites.Count) sites" -ForegroundColor Yellow
foreach ($user in $TargetUsers) {
$userSites = $targetUserPermissions | Where-Object { $_.UserEmail -eq $user }
if ($userSites) {
Write-Host "`n$user has access to $($userSites.Count) sites:" -ForegroundColor Yellow
$userSites | ForEach-Object { Write-Host " - $($_.SiteTitle) ($($_.PermissionLevel))" -ForegroundColor Gray }
}
}
}
}
else {
Write-Host "No permissions data collected" -ForegroundColor Yellow
}
}
# Run the report
Start-PermissionsReport
# Disconnect from SharePoint Online
Disconnect-SPOService
To use this script effectively for your migration planning:
The script will generate a CSV report with the following columns:
SiteUrl
SiteTitle
UserEmail
DisplayName
PermissionLevel (Site Collection Administrator or Site Member)
UserType
IsTargetUser (Yes/No if you specified target users)
For migration planning, you can then:
Filter the CSV by your target users to see which sites they access
Group by SiteUrl to see all users for each site
Identify sites with only your target users (candidates for migration)
Identify shared sites that might need special consideration
Would you like me to add any additional features, such as checking for specific permission levels, group memberships, or integration with Microsoft Graph for more detailed permissions?
User
My tenant does not allow legacy authentication.
Assistant
You're right - modern authentication is required. Let me provide you an updated script that uses the PnP PowerShell module, which supports modern authentication and provides more detailed permission information.
# SharePoint Online User Permissions Report Script - Modern Auth Version
# Uses PnP PowerShell for modern authentication support
# Parameters
param(
[Parameter(Mandatory=$false)]
[string]$OutputPath = ".\SPO_Permissions_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv",
[Parameter(Mandatory=$false)]
[string[]]$TargetUsers = @(), # Array of user emails to specifically track
[Parameter(Mandatory=$false)]
[switch]$IncludeOneDrivesSites = $false,
[Parameter(Mandatory=$false)]
[switch]$UseInteractive = $true # Use interactive login (recommended)
)
# Check if PnP.PowerShell module is installed
function Ensure-PnPModule {
if (!(Get-Module -ListAvailable -Name "PnP.PowerShell")) {
Write-Host "PnP.PowerShell module not found. Installing..." -ForegroundColor Yellow
try {
Install-Module -Name "PnP.PowerShell" -Force -AllowClobber -Scope CurrentUser
Write-Host "PnP.PowerShell module installed successfully" -ForegroundColor Green
}
catch {
Write-Host "Failed to install PnP.PowerShell module: $_" -ForegroundColor Red
Write-Host "Please install manually: Install-Module -Name PnP.PowerShell" -ForegroundColor Yellow
exit
}
}
Import-Module PnP.PowerShell -Force
}
# Connect to SharePoint Admin Center
function Connect-SharePointAdmin {
$tenantUrl = Read-Host "Enter your tenant name (e.g., contoso for contoso.sharepoint.com)"
$adminUrl = "https://$tenantUrl-admin.sharepoint.com"
try {
if ($UseInteractive) {
Connect-PnPOnline -Url $adminUrl -Interactive
}
else {
# For automated scenarios, you can use other auth methods
Connect-PnPOnline -Url $adminUrl -UseWebLogin
}
Write-Host "Successfully connected to SharePoint Admin Center" -ForegroundColor Green
return $adminUrl
}
catch {
Write-Host "Failed to connect to SharePoint Admin Center: $_" -ForegroundColor Red
exit
}
}
# Get all site collections
function Get-AllSiteCollections {
Write-Host "Retrieving all site collections..." -ForegroundColor Yellow
try {
# Get all sites including modern team and communication sites
$sites = Get-PnPTenantSite -IncludeOneDriveSites:$IncludeOneDrivesSites
if (-not $IncludeOneDrivesSites) {
$sites = $sites | Where-Object { $_.Url -notlike "*/personal/*" }
}
Write-Host "Found $($sites.Count) site collections" -ForegroundColor Green
return $sites
}
catch {
Write-Host "Error retrieving sites: $_" -ForegroundColor Red
return @()
}
}
# Get detailed permissions for a site
function Get-SitePermissions {
param(
[Parameter(Mandatory=$true)]
$Site
)
$permissions = @()
try {
# Connect to the specific site
Connect-PnPOnline -Url $Site.Url -Interactive
# Get site admins
$siteAdmins = Get-PnPSiteCollectionAdmin
foreach ($admin in $siteAdmins) {
if ($admin.Email) {
$permissions += [PSCustomObject]@{
SiteUrl = $Site.Url
SiteTitle = $Site.Title
UserEmail = $admin.Email
DisplayName = $admin.Title
PermissionLevel = "Site Collection Administrator"
PermissionType = "Direct"
GroupMembership = "N/A"
IsTargetUser = if ($TargetUsers -contains $admin.Email) { "Yes" } else { "No" }
LastModified = $Site.LastContentModifiedDate
SiteTemplate = $Site.Template
StorageUsed = [math]::Round($Site.StorageUsageCurrent / 1024, 2) # Convert to GB
}
}
}
# Get all site groups and their members
$siteGroups = Get-PnPGroup
foreach ($group in $siteGroups) {
try {
$groupMembers = Get-PnPGroupMember -Identity $group.Id
foreach ($member in $groupMembers) {
if ($member.Email -and $member.PrincipalType -eq "User") {
# Skip system accounts
if ($member.Email -notlike "*#ext#*" -and
$member.Email -notlike "app@*" -and
$member.LoginName -notlike "SHAREPOINT\*" -and
$member.LoginName -notlike "c:0*") {
# Determine permission level based on group name
$permissionLevel = switch -Wildcard ($group.Title) {
"*Owners*" { "Full Control" }
"*Members*" { "Edit" }
"*Contributors*" { "Contribute" }
"*Visitors*" { "Read" }
default { $group.Title }
}
$permissions += [PSCustomObject]@{
SiteUrl = $Site.Url
SiteTitle = $Site.Title
UserEmail = $member.Email
DisplayName = $member.Title
PermissionLevel = $permissionLevel
PermissionType = "Group"
GroupMembership = $group.Title
IsTargetUser = if ($TargetUsers -contains $member.Email) { "Yes" } else { "No" }
LastModified = $Site.LastContentModifiedDate
SiteTemplate = $Site.Template
StorageUsed = [math]::Round($Site.StorageUsageCurrent / 1024, 2)
}
}
}
}
}
catch {
Write-Host "Error processing group $($group.Title): $_" -ForegroundColor Yellow
}
}
# Get users with direct permissions (not through groups)
$web = Get-PnPWeb -Includes RoleAssignments
$ctx = Get-PnPContext
foreach ($ra in $web.RoleAssignments) {
$ctx.Load($ra.Member)
$ctx.Load($ra.RoleDefinitionBindings)
$ctx.ExecuteQuery()
if ($ra.Member.PrincipalType -eq "User" -and $ra.Member.Email) {
$roleNames = $ra.RoleDefinitionBindings | ForEach-Object { $_.Name }
if ($ra.Member.Email -notlike "*#ext#*" -and
$ra.Member.Email -notlike "app@*") {
$permissions += [PSCustomObject]@{
SiteUrl = $Site.Url
SiteTitle = $Site.Title
UserEmail = $ra.Member.Email
DisplayName = $ra.Member.Title
PermissionLevel = $roleNames -join ", "
PermissionType = "Direct"
GroupMembership = "Direct Permission"
IsTargetUser = if ($TargetUsers -contains $ra.Member.Email) { "Yes" } else { "No" }
LastModified = $Site.LastContentModifiedDate
SiteTemplate = $Site.Template
StorageUsed = [math]::Round($Site.StorageUsageCurrent / 1024, 2)
}
}
}
}
}
catch {
Write-Host "Error processing site $($Site.Url): $_" -ForegroundColor Red
}
return $permissions
}
# Main execution
function Start-PermissionsReport {
Write-Host "`nStarting SharePoint Online Permissions Report Generation" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
# Ensure PnP module is available
Ensure-PnPModule
# Connect to SPO Admin
$adminUrl = Connect-SharePointAdmin
# Get all sites
$allSites = Get-AllSiteCollections
if ($allSites.Count -eq 0) {
Write-Host "No sites found to process" -ForegroundColor Yellow
return
}
# Process each site
$allPermissions = @()
$processedCount = 0
$errors = @()
foreach ($site in $allSites) {
$processedCount++
Write-Progress -Activity "Processing SharePoint Sites" -Status "Processing $($site.Url)" -PercentComplete (($processedCount / $allSites.Count) * 100)
Write-Host "Processing site $processedCount of $($allSites.Count): $($site.Url)" -ForegroundColor Gray
try {
$sitePermissions = Get-SitePermissions -Site $site
$allPermissions += $sitePermissions
}
catch {
$errors += "Failed to process $($site.Url): $_"
}
}
Write-Progress -Activity "Processing SharePoint Sites" -Completed
# Export results
if ($allPermissions.Count -gt 0) {
# Remove duplicates (same user might appear multiple times)
$allPermissions = $allPermissions | Sort-Object SiteUrl, UserEmail, PermissionLevel -Unique
$allPermissions | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Host "`nReport generated successfully!" -ForegroundColor Green
Write-Host "Total permission entries found: $($allPermissions.Count)" -ForegroundColor Green
Write-Host "Report saved to: $OutputPath" -ForegroundColor Green
# If target users were specified, show summary
if ($TargetUsers.Count -gt 0) {
Write-Host "`nTarget User Summary:" -ForegroundColor Cyan
$targetUserPermissions = $allPermissions | Where-Object { $_.IsTargetUser -eq "Yes" }
$targetSites = $targetUserPermissions | Select-Object -ExpandProperty SiteUrl -Unique
Write-Host "Target users found in $($targetSites.Count) sites" -ForegroundColor Yellow
# Create a summary report for target users
$summaryPath = $OutputPath.Replace(".csv", "_TargetUserSummary.csv")
$summary = @()
foreach ($user in $TargetUsers) {
$userSites = $targetUserPermissions | Where-Object { $_.UserEmail -eq $user }
if ($userSites) {
Write-Host "`n$user has access to $($userSites.Count) permission entries:" -ForegroundColor Yellow
$userSiteList = $userSites | Select-Object -ExpandProperty SiteUrl -Unique
foreach ($siteUrl in $userSiteList) {
$sitePerms = $userSites | Where-Object { $_.SiteUrl -eq $siteUrl }
$summary += [PSCustomObject]@{
User = $user
SiteUrl = $siteUrl
SiteTitle = $sitePerms[0].SiteTitle
Permissions = ($sitePerms | ForEach-Object { "$($_.PermissionLevel) ($($_.PermissionType))" }) -join "; "
StorageGB = $sitePerms[0].StorageUsed
LastModified = $sitePerms[0].LastModified
}
}
}
else {
Write-Host "`n$user - No sites found" -ForegroundColor Yellow
}
}
if ($summary.Count -gt 0) {
$summary | Export-Csv -Path $summaryPath -NoTypeInformation
Write-Host "`nTarget user summary saved to: $summaryPath" -ForegroundColor Green
}
}
# Show errors if any
if ($errors.Count -gt 0) {
Write-Host "`nErrors encountered:" -ForegroundColor Yellow
$errors | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
}
}
else {
Write-Host "No permissions data collected" -ForegroundColor Yellow
}
}
# Run the report
Start-PermissionsReport
# Disconnect
Disconnect-PnPOnline
This updated script:
Uses PnP PowerShell which fully supports modern authentication
Provides more detailed information including:
Permission types (Direct vs Group-based)
Group memberships
Site templates
Storage usage
Last modified dates
Creates two reports when target users are specified:
Full permissions report
Target user summary report
To use the script:
powershell
# Basic usage with interactive login
.\Get-SPOPermissions.ps1
# Track specific users
.\Get-SPOPermissions.ps1 -TargetUsers @("user1@domain.com", "user2@domain.com")
# Include OneDrive sites
.\Get-SPOPermissions.ps1 -IncludeOneDrivesSites -TargetUsers @("user1@domain.com")
The script will prompt for interactive authentication, which works with MFA and conditional access policies. This approach is much more secure and aligns with Microsoft's modern authentication requirements.