I had similar request last week and wrote this PowerShell Script with ChatGPT.
You need to connect to SPO first (connect and disconnect commented out).
# Requires the SharePoint Online Management Shell
# Ensure you have the required permissions to manage OneDrive access
# Define logging function
Function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO"
)
$Timestamp = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Write-Host "$($Timestamp) [$($Level)] $($Message)"
"$($Timestamp) [$($Level)] $($Message)" | Out-File -Append -FilePath "onedrive_access.log"
}
# Debug function
Function Debug-Mode {
param (
[switch]$Enable
)
$script:Debug = $Enable
}
# Grant Full Access to OneDrive
Function Grant-OneDriveAccess {
param (
[string]$AdminSiteUrl, # SharePoint Admin Center URL
[string]$TargetUserUPN, # User B's UPN
[string]$AccessUserUPN # User A's UPN
)
try {
Write-Log "Connecting to SharePoint Admin Center..."
#Connect-SPOService -Url $AdminSiteUrl
Write-Log "Constructing OneDrive URL for $($TargetUserUPN)..."
# Construct the OneDrive URL assuming standard tenant URL pattern
$TenantName = ($AdminSiteUrl -split '-admin\.')[0] -replace 'https://', ''
$OneDriveUrl = "https://$($TenantName)-my.sharepoint.com/personal/$($TargetUserUPN -replace '@', '_' -replace '.com','_com')/" # CHANGE IF NEEDED
Write-Log "OneDrive URL constructed: $($OneDriveUrl)"
Write-Log "Granting $($AccessUserUPN) full control to $($TargetUserUPN)'s OneDrive ($($OneDriveUrl))..."
if ($Debug) {
Write-Log "Debug mode enabled. Skipping permission assignment." "DBG"
} else {
Set-SPOUser -Site $OneDriveUrl -LoginName $AccessUserUPN -IsSiteCollectionAdmin $true -ErrorAction Stop
Write-Log "$($AccessUserUPN) granted full control to $($TargetUserUPN)'s OneDrive." "INFO"
}
} catch {
Write-Log "Error: $($_.Exception.Message)" "ERR"
} finally {
Write-Log "Disconnecting from SharePoint Online..."
#Disconnect-SPOService
}
}
# Main script
Function Main {
param (
[string]$AdminSiteUrl, # Example: "https://tenant-admin.sharepoint.com"
[string]$TargetUserUPN, # User B's UPN
[string]$AccessUserUPN, # User A's UPN
[switch]$EnableDebug
)
Debug-Mode -Enable:$EnableDebug
Write-Log "Processing: Granting $($AccessUserUPN) access to $($TargetUserUPN)'s OneDrive..."
Grant-OneDriveAccess -AdminSiteUrl $AdminSiteUrl -TargetUserUPN $TargetUserUPN -AccessUserUPN $AccessUserUPN
Write-Log "Script execution completed." "INFO"
}
# Example usage
# Provide the SharePoint Admin Center URL and input UPNs
# Debug mode can be enabled to simulate actions without applying changes
$AdminSiteUrl = "https://YOURTENANT-admin.sharepoint.com"
$TargetUserUPN = "" # Replace with User B's UPN
$AccessUserUPN = "" # Replace with User A's UPN
$EnableDebug = $false
Main -AdminSiteUrl $AdminSiteUrl -TargetUserUPN $TargetUserUPN -AccessUserUPN $AccessUserUPN -EnableDebug:$EnableDebug