Moving files from OneDrive to Teams via Powershell
Question
While it is possible to move files between Teams sites and between OneDrive users, it does not seem feasible to move files from Teams to OneDrive and vice versa, using Powershell.
The restriction is happening due to the domain differences between OneDrive and Teams.
OneDrive URL: https://org-my.sharepoint.com
Teams URL: https://org.sharepoint.com
After connecting to one of the above you are only able to use relative URLs with the Move-PnPFile command and will be unable to point to the other domain.
Eg.
Connect-PnPOnline -Url https://org.sharepoint.com
Move-PnpFile -ServerRelativeUrl "/teams/MyTeam/Documents" -TargetServerRelativeLibrary "/personal/user_domain_com/Documents/"
Will throw an error due to not locating the target.
How can we transfer files between these domains in the same organization without downloading and uploading files to/from a local disk?
La solution
You may consider using CSOM MoveCopyUtil.MoveFile
method:
CSOM PowerShell code:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Function to Move a File
Function Move-SPOFile([String]$SiteURL, [String]$SourceFileURL, [String]$TargetFileURL)
{
Try{
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#sharepoint online powershell to move files
$MoveCopyOpt = New-Object Microsoft.SharePoint.Client.MoveCopyOptions
$Overwrite = $True
[Microsoft.SharePoint.Client.MoveCopyUtil]::MoveFile($Ctx, $SourceFileURL, $TargetFileURL, $Overwrite, $MoveCopyOpt)
$Ctx.ExecuteQuery()
Write-host -f Green "File Moved Successfully!"
}
Catch {
write-host -f Red "Error Moving the File!" $_.Exception.Message
}
}
#Set Config Parameters
$SiteURL="https://abc.sharepoint.com/sites/s01"
$SourceFileURL="https://abc.sharepoint.com/sites/s01/Shared Documents/test_34982.txt"
$TargetFileURL="https://abc-my.sharepoint.com/personal/admin_abc_onmicrosoft_com/Documents/test_34982.txt"
#Get Credentials to connect
$Cred= Get-Credential
#Call the function to Move the File
Move-SPOFile $SiteURL $SourceFileURL $TargetFileURL
I have tested it on my SPO environment and it works fine.
BR