Streamlining SharePoint Site Permissions with PowerShell

Managing site permissions in SharePoint can be a complex task, especially for organizations with multiple sites and users. This PowerShell script automates the process of retrieving and updating permissions for SharePoint sites, enabling administrators to efficiently manage access and ensure compliance with security policies.
This script will:
1. Connect to the SharePoint site using PowerShell.
2. Retrieve the current permissions for a specified site.
3. Update permissions to add or remove access for users or groups.
By implementing this automated approach, IT administrators can save time and improve the security posture of their SharePoint environment.

# Install SharePoint Online Management Shell if not already installed
if (-Not (Get-Module -ListAvailable -Name Microsoft.Online.SharePoint.PowerShell)) {
    Install-Module -Name Microsoft.Online.SharePoint.PowerShell -Scope CurrentUser -AllowClobber
}
# Connect to SharePoint Online
$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"
$credential = Get-Credential
Connect-SPOService -Url $siteUrl -Credential $credential
# Retrieve current permissions
$permissions = Get-SPOSiteGroup -Site $siteUrl
Write-Host "=== Current Permissions for $siteUrl ==="
foreach ($group in $permissions) {
    Write-Host "Group: $($group.Title)"
}
# Update permissions: Add or Remove Users
$action = Read-Host "Do you want to add or remove users? (add/remove)"
$userEmail = Read-Host "Enter the user's email"
switch ($action.ToLower()) {
    "add" {
        Add-SPOUser -Group $group.Title -LoginName $userEmail -Site $siteUrl
        Write-Host "Added $userEmail to $($group.Title) group."
    }
    "remove" {
        Remove-SPOUser -Group $group.Title -LoginName $userEmail -Site $siteUrl
        Write-Host "Removed $userEmail from $($group.Title) group."
    }
    default {
        Write-Host "Invalid action specified."
    }
}
# Disconnect from SharePoint
Disconnect-SPOService
Write-Host "Permissions management actions completed."