← script library

Automating OneDrive User Permissions Management with PowerShell

SharePoint & OneDriveDecember 23, 2024

Managing user permissions in OneDrive is essential for ensuring data security and proper access control. This PowerShell script helps administrators automate the process of retrieving and updating file permissions in OneDrive, making it easier to manage who has access to critical documents and folders. This script will: 1. Connect to OneDrive using Microsoft Graph. 2. Retrieve a list of files and their current permissions. 3. Allow for updating permissions for specific users or groups. By using this script, IT administrators can efficiently oversee permissions across OneDrive, enhancing compliance and security measures.

powershell
# Install Microsoft Graph PowerShell module if not already installed
if (-Not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Install-Module -Name Microsoft.Graph -Scope CurrentUser -AllowClobber
}
# Connect to Microsoft Graph
Connect-MgGraph -Scopes 'Files.ReadWrite.All', 'Sites.Read.All'
# Define required parameters
$siteId = "your-tenant-id"  # Replace with your SharePoint site ID
$driveId = "your-drive-id"   # Replace with the OneDrive drive ID
$fileId = "your-file-id"    # Specify the file ID or path
# Retrieve file permissions
$fileItem = Get-MgDriveItem -DriveId $driveId -ItemId $fileId
$permissions = Get-MgDriveItemPermission -DriveId $driveId -ItemId $fileItem.Id
Write-Host "=== Current Permissions for $($fileItem.Name) ==="
foreach ($permission in $permissions) {
    Write-Host "Role: $($permission.Roles) - Granted To: $($permission.GrantedTo.User.DisplayName)"
}
# Update permissions (example for adding a user)
$newUserEmail = "[email protected]"  # Email of the user to add
$newRole = "read"  # Options: read, write
New-MgDriveItemPermission -DriveId $driveId -ItemId $fileItem.Id -Body @{
    roles = @($newRole)
    grantedTo = @{
        user = @{ email = $newUserEmail }
    }
}
Write-Host "Updated permissions for $newUserEmail on file $($fileItem.Name)."
# Disconnect from Microsoft Graph
Disconnect-MgGraph
Write-Host "Permissions management process completed."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.