Permission management on SharePoint is a painful process if you’ve got a large quantity of sites to manage, so some level of automation using PowerShell can definitely help.

There’s a lot of variation to what you can do with PowerShell, assign permissions in bulk, remove users from site groups with a simple command, and even generate reports on current user roles for auditing purposes.

The script below is a combination of a few tasks that you might use. The script does the following:

  • Assigns users to different groups (Owners, Members, Visitors) based on predefined lists.
  • Removes specific users from SharePoint site groups, ensuring permissions are updated dynamically.
  • Exports permission details to a CSV file for auditing, allowing administrators to keep track of user access.

Before running the script, you’ll need the following:

  • Microsoft.Online.SharePoint.PowerShell installed
  • SharePoint Administrator role for your tenant
  • PowerShell 5

# Define the admin center URL
$adminCenterURL = "https://yourdomain-admin.sharepoint.com"

# Connect to SharePoint Online
Connect-SPOService -Url $adminCenterURL

# Define site URL
$siteURL = "https://yourdomain.sharepoint.com/sites/YourSite"

# List of users to add with their permission levels
$users = @(
    @{Email = "user1@yourdomain.com"; Group = "Members"},
    @{Email = "user2@yourdomain.com"; Group = "Owners"},
    @{Email = "user3@yourdomain.com"; Group = "Visitors"}
)

# Add users to groups
foreach ($user in $users) {
    Set-SPOSiteGroup -Site $siteURL -Group $user.Group -User $user.Email
    write-host "User $($user.Email) has been assigned to $($user.Group) in $siteURL"
}

# Function to remove a user from a site group
function Remove-UserFromGroup
{
    param (
        [string]$SiteURL,
        [string]$UserEmail
    )
    Remove-SPOUser -Site $SiteURL -LoginName $UserEmail
    write-host "User $UserEmail has been removed from $SiteURL"
}

# Example usage to remove a user
Remove-UserFromGroup -SiteURL $siteURL -UserEmail "user1@yourdomain.com"

# Export current permissions to CSV
$siteGroups = Get-SPOSiteGroup -Site $siteURL
$groupPermissions = @()

foreach ($group in $siteGroups)
{
    foreach ($user in $group.Users)
    {
        $groupPermissions += [PSCustomObject]@
        {
            Group = $group.Title
            User = $user.LoginName
        }
    }
}

$groupPermissions | Export-Csv -Path "Permissions.csv" -NoTypeInformation
Write-host "Permissions have been exported to SharePointPermissions.csv"

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply