9 PowerShell Scripts Every SharePoint Admin Needs for Ironclad Auditing + Video

Listen to this Post

Featured Image

Introduction:

In the realm of Microsoft 365, SharePoint Online serves as the backbone of collaboration, but its flexibility often creates a massive attack surface. Security teams frequently operate in a reactive mode, only investigating permissions after a data leak has occurred. By the time an anonymous link is discovered or an external user exfiltrates data, the confidentiality breach is already complete. Leveraging PowerShell for proactive, continuous auditing transforms security from a forensic exercise to a preventative measure, granting administrators complete visibility over file access, permission changes, and external sharing anomalies.

Learning Objectives:

  • Understand how to automate the detection of over-permissive and anonymous sharing links in SharePoint.
  • Learn to monitor external user activity and track group permission changes using PowerShell.
  • Gain the ability to map Teams-connected SharePoint sites and correlate user access patterns.

You Should Know:

1. Auditing File Downloads, Access, and Deletions

To understand the “who, what, and when” of your data, you must dig into the Unified Audit Logs. While the UI provides surface-level data, PowerShell allows for granular filtering.
What it does: This script connects to the Exchange Online Management Shell to search audit logs specifically for file operations.

How to use it:

1. Install the Module: `Install-Module -Name ExchangeOnlineManagement`

2. Connect: `Connect-ExchangeOnline`

3. Run the Search:

Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) -Operations FileAccessed, FileDownloaded, FileDeleted -ResultSize 5000 | Format-Table -AutoSize

4. Export to CSV:

Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -Operations FileDownloaded -ResultSize 5000 | Export-Csv -Path "C:\Audit\FileDownloads.csv" -NoTypeInformation

This is critical for identifying potential data hoarding or unauthorized access patterns.

2. Monitoring External User Activity

External collaboration is a necessity, but it requires strict oversight. You need to differentiate between legitimate partners and potential threats.
What it does: The script filters audit logs to isolate actions performed by users outside your tenant domain.

Step-by-step guide:

  1. Retrieve all audit logs for external users by filtering on the `UserId` property.
  2. Use a regex or string match to exclude your primary domain (e.g., @yourcompany.com).

3. Script Logic:

$Logs = Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) -ResultSize 10000
$ExternalActivity = $Logs | Where-Object {$_.UserIds -notlike "@yourdomain.com"}
$ExternalActivity | Export-Csv "C:\Audit\ExternalAccess.csv"

4. Review the CSV to see what files external users have accessed or modified.

3. Exporting Anonymous (Anyone) Links

“Anyone” links are the most dangerous type of sharing link because they bypass authentication entirely. They are essentially backdoors into your environment.
What it does: This script utilizes the PnP PowerShell module to scan site collections for sharing links that grant access to “Everyone.”

Step-by-step guide:

1. Install PnP Module: `Install-Module PnP.PowerShell -Scope CurrentUser`

  1. Connect to Site: `Connect-PnPOnline -Url “https://yourtenant.sharepoint.com/sites/yoursite” -Interactive`

3. Get All Sharing Links:

Get-PnPSharingLink | Where-Object {$_.LinkKind -eq "AnonymousAccess"} | Export-Csv -Path "C:\Audit\AnonymousLinks.csv"

4. For all sites: Loop through a CSV list of your site collections and run the command against each one. The output will show you exactly which files are exposed to the open internet.

4. Tracking Group Permission Changes

Privilege escalation often happens subtly through group membership modifications. A user added to a “Site Owners” group can bypass all folder-level permissions.
What it does: Monitors Azure AD and SharePoint groups for changes to membership.

Step-by-step guide (via Audit Logs):

  1. Search for the `Add member to group` and `Remove member from group` operations.

2. PowerShell Command:

Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -Operations "Add member to group", "Remove member from group" -ResultSize 2000 | ForEach-Object {
$AuditData = $<em>.AuditData | ConvertFrom-Json
[bash]@{
Time = $</em>.CreationDate
User = $<em>.UserIds
Operation = $</em>.Operations
Group = $AuditData.ObjectId
Member = $AuditData.Target
}
} | Export-Csv "C:\Audit\GroupChanges.csv"

3. Analyze the CSV to ensure no unauthorized users have been added to high-privilege groups.

5. Mapping Teams-linked SharePoint Sites

Microsoft Teams creates a backend SharePoint site for every team. These sites are often forgotten, leading to “shadow data” that isn’t properly governed.
What it does: Identifies all SharePoint sites connected to Microsoft Teams.

Step-by-step guide:

  1. Connect to SharePoint Online Management Shell: `Connect-SPOService -Url https://yourtenant-admin.sharepoint.com`
  2. Get all sites with the GroupId property (Teams):
    Get-SPOSite -IncludePersonalSite $false -Limit All | Where-Object {$_.GroupId -ne $null} | Select-Object Url, , GroupId, Status
    
  3. Export the list to cross-reference with active Teams. If a Team is deleted but the site remains, this is a data remnant that needs to be cleaned up.

6. Auditing Site Collection Administrators

Site Collection Admins have god-level access. Regularly auditing these lists prevents “Admin sprawl” where former employees or contractors retain excessive privileges.
What it does: Iterates through all site collections and lists the administrators.

Step-by-step guide:

1. Get all Site Collections:

$Sites = Get-SPOSite -Limit All

2. Loop and Retrieve Admins:

$Results = @()
foreach ($Site in $Sites) {
$Admins = Get-SPOSite -Identity $Site.Url | Select -ExpandProperty Owners
$Results += [bash]@{
SiteUrl = $Site.Url
Admins = $Admins.Email -join "; "
}
}
$Results | Export-Csv "C:\Audit\SiteAdmins.csv"

7. Identifying Inactive External Users

External users who have not accessed the tenant in 90+ days pose a risk. Their accounts are prime targets for takeover.
What it does: Queries Azure AD for guest users and checks their last sign-in time.

Step-by-step guide:

1. Install Azure AD Module: `Install-Module AzureAD`

2. Connect: `Connect-AzureAD`

3. Find stale guests:

Get-AzureADUser -Filter "userType eq 'Guest'" -All $true | Where-Object {
$_.RefreshTokensValidFromDateTime -lt (Get-Date).AddDays(-90)
} | Select-Object DisplayName, Mail, UserPrincipalName

4. Action: Review this list and consider removing access or requiring re-invitation.

  1. Checking for Overshared Folders at the Root Level
    Sometimes, users share entire document libraries or root folders, granting excessive permissions downstream.
    What it does: Scans for unique permissions (permission breaks) on high-level objects.

Step-by-step guide:

  1. Get PnP Context: `Connect-PnPOnline -Url “https://yourtenant.sharepoint.com/sites/yoursite”`

2. Get Folder Permissions:

Get-PnPFolder -FolderUrl "Shared Documents" -Includes ListItemAllFields.ParentList, ListItemAllFields.HasUniqueRoleAssignments

3. Check HasUniqueRoleAssignments: If True, this folder has permissions that differ from its parent. Investigate why it was broken out of inheritance.

9. Generating a Comprehensive Permissions Matrix

A flat file (CSV) export of all users and their access levels across all sites is invaluable for compliance audits (ISO 27001, SOC2).
What it does: Aggregates user permissions across multiple sites into a single report.

Step-by-step guide:

  1. Use the PnP PowerShell `Get-PnPUser` and `Get-PnPGroupMembers` cmdlets.
  2. For each site, map the user to their associated groups (Visitors, Members, Owners).

3. Export Logic:

Connect-PnPOnline -Url $SiteUrl -Interactive
$Users = Get-PnPUser | Where-Object {$<em>.IsHiddenInUI -eq $false}
$Users | Select , Email, LoginName, @{Name="Groups";Expression={($</em>.Groups | Select -ExpandProperty ) -join ";"}} | Export-Csv "C:\Audit\UserMatrix.csv" -Append

What Undercode Say:

The core issue highlighted here is the necessity of shifting from manual, reactionary audits to continuous, automated monitoring. The PowerShell scripts provided by the original post serve as a digital microscope, revealing the microscopic cracks in SharePoint’s armor that often go unnoticed until a breach occurs. Relying on the native admin center for oversight is like trying to secure a fortress by only looking at the front gate; these scripts allow you to patrol the entire perimeter, including the forgotten tunnels (Teams sites) and unlocked windows (anonymous links).

Key Takeaway 1: Automation is non-negotiable. Running these scripts on a scheduled basis (via Azure Automation or Task Scheduler) ensures that you have a historical baseline. If a file is deleted at 2:00 AM on a Saturday, you want the audit log waiting for you Monday morning, not a frantic call from legal.

Key Takeaway 2: Focus on “Anonymous Links” and “External Users” first. These represent the highest risk to data confidentiality. By prioritizing the identification of these two vectors, you close the most common pathways for data leaks in modern cloud collaboration environments. The ability to export these findings to CSV allows security teams to communicate risks to management in a clear, data-driven format.

Prediction:

As hybrid work solidifies, we will see a convergence of SharePoint security with Identity Threat Detection and Response (ITDR) systems. The manual PowerShell audits we run today will be replaced by AI-driven platforms that analyze these same data points (external access, anonymous links, group changes) in real-time to detect anomalous behavior. The future won’t just be about what permission was changed, but why it was changed and whether the user’s behavior deviates from their baseline—flagging a compromised admin account before they can exfiltrate the data these scripts are trying to protect.

▶️ Related Video (88% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Pavithra Pavee – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky