Automate OneDrive File Sharing with PowerShell

In this post, we will explore a useful PowerShell script that automates the process of sharing files on OneDrive. This script is perfect for businesses looking to streamline collaboration by easily granting access to files for team members without navigating through the OneDrive interface each time. Whether you need to share a single file or multiple files in a folder, this script will simplify the process, saving you time and effort.
Here is the PowerShell script to share files in OneDrive:

# Import the required module
Import-Module Microsoft.Online.SharePoint.PowerShell
# Define the OneDrive user and file to share
$oneDriveUser = "[email protected]"
$filePath = "/Shared Documents/MyFile.txt"
$shareWithUser = "[email protected]"
# Connect to SharePoint Online
$credential = Get-Credential
Connect-SPOService -Url "https://yourtenant-admin.sharepoint.com" -Credential $credential
# Share the file
Set-SPOUser -Site "https://yourtenant-my.sharepoint.com/personal/user_example_com" -LoginName $shareWithUser -IsSiteCollectionAdmin $true
# Grant access to the file
Set-SPOSharingLink -Path $filePath -LinkType View -User $shareWithUser
Write-Host "File shared successfully with $shareWithUser."