In this article, we will discuss a PowerShell script that allows you to copy all OneDrive files from one user to another user. This is particularly useful when an employee leaves an organization, and their files need to be transferred to a different user. This process is crucial in maintaining the organization’s data continuity and ensuring that vital files are retained. The script takes care of copying files, creating directory structures, and handling errors.
Also see: How to Check Office 365 User License Using PowerShell
Page Contents
Prerequisites
To successfully execute this script, you will need the following PowerShell modules:
- MSOnline: This module is used for managing Azure Active Directory.
- SharePointPnPPowerShellOnline: This module is used for interacting with SharePoint Online.
- SharePoint Online Management Shell: This module is used for managing SharePoint Online site collections.
To install the MSOnline module, run the following command:
Install-Module MSOnline
To install the SharePointPnPPowerShellOnline module, run the following command:
Install-Module SharePointPnPPowerShellOnline
To install the SharePoint Online Management Shell, follow these steps:
- Visit the SharePoint Online Management Shell download page.
- Click on the “Download” button.
- Once the download is complete, run the installer and follow the on-screen instructions to complete the installation.
Once all the required modules have been installed, you can proceed to run the script.
Transferring all OneDrive files to another user via PowerShell
The following PowerShell script is designed to automate the process of copying all files and folders from a departing user’s OneDrive to a destination user’s OneDrive within a Microsoft Office 365 environment. This script is an invaluable tool for system administrators when managing files and folders during employee transitions or other scenarios where transferring OneDrive content is required.
$departingUserEmail = Read-Host "Enter the email address of the user who is leaving"
$destinationUserEmail = Read-Host "Enter the email address of the destination user"
$adminUsername = Read-Host "Enter the username of the Global Admin account"
$adminCredentials = Get-Credential -Credential $adminUsername
Connect-MsolService -Credential $adminCredentials
$initialDomain = Get-MsolDomain | Where-Object {$_.IsInitial -eq $true}
$sharePointAdminURL = "https://$($initialDomain.Name.Split(".")[0])-admin.sharepoint.com"
$departingUserUnderscore = $departingUserEmail -replace "[^a-zA-Z]", "_"
$destinationUserUnderscore = $destinationUserEmail -replace "[^a-zA-Z]", "_"
$departingOneDriveSite = "https://$($initialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$departingUserUnderscore"
$destinationOneDriveSite = "https://$($initialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$destinationUserUnderscore"
Write-Host "`nEstablishing connection to SharePoint Online" -ForegroundColor Blue
Connect-SPOService -Url $sharePointAdminURL -Credential $adminCredentials
Write-Host "`nGranting administrative access to $adminUsername on both OneDrive site collections" -ForegroundColor Blue
Set-SPOUser -Site $departingOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $true
Set-SPOUser -Site $destinationOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $true
Write-Host "`nConnecting to $departingUserEmail's OneDrive using SharePoint Online PNP module" -ForegroundColor Blue
Connect-PnPOnline -Url $departingOneDriveSite -Credentials $adminCredentials
Write-Host "`nRetrieving display name of $departingUserEmail" -ForegroundColor Blue
$departingUser = Get-PnPSiteCollectionAdmin | Where-Object {$_.loginname -match $departingUserEmail}
if ($departingUser -contains $null) {
$departingUser = @{
Title = "Departing User"
}
}
$departingOneDrivePath = "/personal/$departingUserUnderscore/Documents"
$destinationOneDrivePath = "/personal/$destinationUserUnderscore/Documents/$($departingUser.Title)'s Files"
$destinationOneDriveSiteRelativePath = "Documents/$($departingUser.Title)'s Files"
Write-Host "`nFetching all items from $($departingUser.Title)" -ForegroundColor Blue
$items = Get-PnPListItem -List Documents -PageSize 1000
$largeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -ge 261095424 -and $_.FileSystemObjectType -contains "File"}
if ($largeItems) {
$largeExport = @()
foreach ($item in $largeItems) {
$largeExport += "$(Get-Date) - Size: $([math]::Round(($item.FieldValues.SMTotalFileStreamSize / 1MB),2)) MB Path: $($item.FieldValues.FileRef)"
Write-Host "File size exceeds limit: $($item.FieldValues.FileRef)" -ForegroundColor DarkYellow
}
$largeExport | Out-file C:\LargeFiles.txt -Append
Write-Host "A list of files exceeding the size limit from $($departingUser.Title) has been exported to C:\LargeFiles.txt" -ForegroundColor Yellow
}
$rightSizeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -lt 261095424 -or $_.FileSystemObjectType -contains "Folder"}
Write-Host "`nConnecting to $destinationUserEmail's OneDrive using SharePoint PNP PowerShell module" -ForegroundColor Blue
Connect-PnPOnline -Url $destinationOneDriveSite -Credentials $adminCredentials
Write-Host "`nFiltering items by folders" -ForegroundColor Blue
$folders = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "Folder"}
Write-Host "`nCreating directory structure" -ForegroundColor Blue
foreach ($folder in $folders) {
$path = ('{0}{1}' -f $destinationOneDriveSiteRelativePath, $folder.fieldvalues.FileRef).Replace($departingOneDrivePath, '')
Write-Host "Creating folder in $path" -ForegroundColor Green
$newFolder = Ensure-PnPFolder -SiteRelativePath $path
}
Write-Host "`nCopying files" -ForegroundColor Blue
$files = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "File"}
$fileErrors = ""
foreach ($file in $files) {
$destPath = ("$destinationOneDrivePath$($file.fieldvalues.FileDirRef)").Replace($departingOneDrivePath, "")
Write-Host "Copying $($file.fieldvalues.FileLeafRef) to $destPath" -ForegroundColor Green
$newFile = Copy-PnPFile -SourceUrl $file.fieldvalues.FileRef -TargetUrl $destPath -OverwriteIfAlreadyExists -Force -ErrorVariable errors -ErrorAction SilentlyContinue
$fileErrors += $errors
}
$fileErrors | Out-File C:\fileErrors.txt
Write-Host "`nRevoking administrative access for $adminUsername on OneDrive site collections" -ForegroundColor Blue
Set-SPOUser -Site $departingOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $false
Set-SPOUser -Site $destinationOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $false
Write-Host "`nProcess completed!" -ForegroundColor Green
Script overview
The PowerShell script provided in this article is designed to automate the process of copying all files and folders from one user’s OneDrive to another user’s OneDrive in a Microsoft Office 365 environment. This script is particularly useful when an employee leaves the organization and their files need to be transferred to another user for reference or continuity purposes. The script performs the following steps:
1. Collecting user input
The script starts by prompting the user for input, which includes the departing user’s email address, the destination user’s email address, and the Global Admin account’s username.
$departingUserEmail = Read-Host "Enter the email address of the user who is leaving" $destinationUserEmail = Read-Host "Enter the email address of the destination user" $adminUsername = Read-Host "Enter the username of the Global Admin account"
2. Connecting to SharePoint online
Using the provided Global Admin account’s username, the script establishes a connection to Microsoft Online Services and retrieves the initial domain for SharePoint and OneDrive. It also constructs the respective URLs for the departing and destination user’s OneDrive site collections.
$adminCredentials = Get-Credential -Credential $adminUsername Connect-MsolService -Credential $adminCredentials
3. Granting administrative access to OneDrive site collections
The script grants administrative access to the Global Admin account on both OneDrive site collections. This allows the Global Admin to manage files and folders within the users’ OneDrive accounts during the transfer process.
Set-SPOUser -Site $departingOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $true Set-SPOUser -Site $destinationOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $true
4. Retrieving files and folders
The script then connects to the departing user’s OneDrive using the SharePoint Online PNP module and retrieves the display name of the departing user.
Connect-PnPOnline -Url $departingOneDriveSite -Credentials $adminCredentials
Afterward, the script fetches all items from the departing user’s OneDrive.
$items = Get-PnPListItem -List Documents -PageSize 1000
It then filters out files that exceed a specific size limit and exports them to a text file.
$largeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -ge 261095424 -and $_.FileSystemObjectType -contains "File"}
The script also filters items that are within the size limit or are folders.
$rightSizeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -lt 261095424 -or $_.FileSystemObjectType -contains "Folder"}
5. Copying files and folders
The script connects to the destination user’s OneDrive using the SharePoint PNP PowerShell module.
Connect-PnPOnline -Url $destinationOneDriveSite -Credentials $adminCredentials
It then filters items by folders and creates a directory structure.
$folders = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "Folder"}
The script copies files from the departing user’s OneDrive to the destination user’s OneDrive and logs any errors in the process.
$files = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "File"} $fileErrors = ""
6. Revoking administrative access
Once the file transfer process is complete, the script revokes the Global Admin’s administrative access to both users’ OneDrive site collections, ensuring security and data privacy.
Set-SPOUser -Site $departingOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $false Set-SPOUser -Site $destinationOneDriveSite -LoginName $adminUsername -IsSiteCollectionAdmin $false Write-Host "Process completed!" -ForegroundColor Green
The script is designed to be efficient and user-friendly while minimizing the risk of errors during the file transfer process. By automating this task, it saves time and effort for administrators who need to transfer files and folders between OneDrive accounts in an Office 365 environment.
Running the script
To run the script, copy and paste it into a PowerShell window. Ensure that you have the necessary prerequisites installed and have Global Administrator access to your Office 365 tenant.
Key takeaways
This PowerShell script streamlines the process of copying all OneDrive data and files from one user to another user, which is particularly useful in cases where an employee leaves the organization. The script handles file copying, directory structure creation, and error handling. Always test the script in a non-production environment before using it in a live scenario to ensure it meets your specific requirements.