Microsoft 365  

OneDrive Sharing Report - PowerShell

Introduction

In this article, we will walk through how to create an Azure AD application that has the necessary permissions to access user data in OneDrive, generate a client secret, and execute a PowerShell script to fetch and report on sharing permissions of OneDrive files.

Steps to Create an Azure AD Application with the Required Permissions

1. Create an Azure AD Application

Follow these steps to register a new Azure AD application in your Microsoft Azure portal:

  • Login to Azure Portal: Visit Azure Portal and sign in using your credentials.
  • Navigate to Azure Active Directory: On the left-hand sidebar, select Azure Active Directory.
  • Register a New Application:
    • In the Azure AD pane, click on App registrations.
    • Click + New registration at the top.
      Request API Permission
    • Name your app (e.g., "OneDrive Sharing Report").
    • Set Supported account types to Accounts in this organizational directory only.
    • Optionally, configure the redirect URI, but it’s not necessary for this script.
    • Click Register to create the application.
  • Note Down the Application (Client) ID and Directory (Tenant) ID: After registration, you’ll be redirected to the application’s overview page. Here, make a note of the Application (client) ID and Directory (tenant) ID.

2. Assign Required Permissions

Now, let's grant the application the permissions it needs to access data in OneDrive:

  • Navigate to API Permissions: In the app registration pane, click on API permissions.
    One drive report
  • Add Permissions: Click + Add a permission, then choose Microsoft Graph under Microsoft APIs.
    Microsoft API
  • Select Application permissions: (since this will be using client credentials flow) and add the following permissions:
    Application permission
    • Directory.Read.All: Allows the app to read directory data.
    • Directory.ReadWrite.All: Allows the app to read and write directory data.
    • Files.Read.All: Allows the app to read all files in OneDrive.
    • Sites.ReadWrite.All: Allows the app to read and write to SharePoint sites, including OneDrive.
    • User.Read: Allows the app to read the signed-in user’s profile.
    • User.Read.All: Allows the app to read all users’ profiles in the organization.
  • Grant Admin Consent: After selecting the required permissions, click Grant admin consent for [Your Organization] to give the app the permissions it needs.

3. Create a Client Secret

The app will need a client secret to authenticate:

  • Navigate to Certificates & Secrets: In the app registration pane, click on Certificates & secrets.
    Certificates and secrets
  • Create a New Client Secret: Under the Client secrets section, click + New client secret.
    Client secrets
  • Provide a description (e.g., "OneDriveScriptSecret") and choose an expiration period.
  • Click Add.
  • Copy the Client Secret: Once the secret is created, make sure to copy the secret value immediately, as you won’t be able to retrieve it again.

4. Use the Client ID, Tenant ID, and Client Secret in the Script

Now that you have the necessary credentials, you'll be able to authenticate with Azure and Microsoft Graph API in the script.

PowerShell Script for Fetching OneDrive Sharing Report

Below is the PowerShell script that utilizes Microsoft Graph API to gather OneDrive file and folder structures, along with sharing permissions.


# Define your Azure AD app credentials
$clientId = ""
$tenantId = ""
$clientSecret = ""

# Prepare the token request URL for Microsoft Graph API
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Create the request body for obtaining an access token
$body = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $clientSecret
    grant_type    = "client_credentials"
}

# Send the request to get the access token
$response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $response.access_token

# Set the authorization header with the access token
$headers = @{
    Authorization = "Bearer $accessToken"
}

# Function to get the list of users in your tenant
function Get-AllUsers {
    $usersUrl = "https://graph.microsoft.com/v1.0/users"
    $users = Invoke-RestMethod -Uri $usersUrl -Headers $headers
    return $users.value
}

# Function to list all files and folders under each user's OneDrive
function Get-UserFiles {
    param(
        [string]$userId
    )
    
    $driveUrl = "https://graph.microsoft.com/v1.0/users/$userId/drive/root/children"
    $driveItems = Invoke-RestMethod -Uri $driveUrl -Headers $headers
    return $driveItems.value
}

# Function to get sharing details and permissions for each user's files/folders in OneDrive
function Get-SharingPermissions {
    param(
        [string]$userId,
        [string]$fileId
    )
    
    $sharingUrl = "https://graph.microsoft.com/v1.0/users/$userId/drive/items/$fileId/permissions"
    $permissions = Invoke-RestMethod -Uri $sharingUrl -Headers $headers
    return $permissions.value
}

# Initialize an array to hold the output data
$outputData = @()

# Main Execution
$users = Get-AllUsers

foreach ($user in $users) {
    Write-Host $user.displayName
    # Get user's OneDrive files and folders
    $files = Get-UserFiles -userId $user.id
    $files | ForEach-Object {
        $fileName = $_.name
        $fileId = $_.id
        $fileType = $_.file.mimeType

        # For each file, collect data on the file itself
        $fileData = New-Object PSObject -property @{
            UserPrincipalName = $user.userPrincipalName
            FileName          = $fileName
            FileId            = $fileId
            FileType          = $fileType
        }

        # Get sharing permissions for each file
        $permissions = Get-SharingPermissions -userId $user.id -fileId $fileId
        $permissions | ForEach-Object {
            # Collect sharing data for each permission entry
            $sharingData = New-Object PSObject -property @{
                UserPrincipalName = $user.userPrincipalName
                FileName          = $fileName
                SharedWith        = $_.grantedTo.user.email
                Permissions       = $_.roles -join ", "
                SharedLink        = $_.link.webUrl
            }

            # Add sharing data to the output array
            $outputData += $sharingData
        }

        # Add file data to the output array (in case there were no sharing permissions)
        if ($permissions.Count -eq 0) {
            $outputData += $fileData
        }
    }
}

# Define the CSV file path
$csvFilePath = "C:\temp\output.csv"

# Export collected data to CSV
$outputData | Export-Csv -Path $csvFilePath -NoTypeInformation

Write-Host "Script execution completed. Data has been saved to $csvFilePath."
            

Script Overview

  • Get-AllUsers: This function retrieves all users from your Azure AD tenant.
  • Get-UserFiles: For each user, this function lists all files and folders in their OneDrive.
  • Get-SharingPermissions: This function collects sharing permissions for each file.
  • Output: The script generates a CSV file containing information about each file’s sharing permissions, including the file name, shared with users, and their roles.

Sample Output (CSV)

UserPrincipalName FileName FileId FileType SharedWith Permissions
[email protected] Document1.txt file123 text [email protected] Reader
[email protected] Spreadsheet.xlsx file124 excel [email protected] Contributor
[email protected] Image.png file125 image [email protected] Reader

Final Notes

  • Ensure that the client ID, tenant ID, and client secret are correctly set.
  • Adjust the $csvFilePath variable to the appropriate location where you want the CSV file to be saved.

By following these steps and running the script, you can automate the process of generating a OneDrive sharing report for all users in your Azure AD tenant.