Azure Automation - Copy Files from one Sharepoint site to another

Viewed 154

I would like to create a workflow that automatically copies files which were uploaded to a Sharepoint-Site onto another SharePoint-Site (for file exchange with customers). Therefore I created a Logic App that triggers a Runbook with following content:

param(
    [Parameter (Mandatory = $true)][string]$FilePath,
    [Parameter (Mandatory = $true)][string]$FileName
)

$Client = "C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.dll"
$ClientRT = "C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path $Client
Add-Type -Path $ClientRT

Creds = Get-AutomationPSCredential -Name "SharepointCreds"
 
#Set parameter values
$TargetSiteURL="https://domain.SharePoint.com/sites/site1"
$SourceSiteURL="https://domain.Sharepoint.com/sites/site2"
 
#Set Source and Destination File URL
$SourceFileURL="/sites/Sitename1/$Filepath/$FileName"
$TargetFileURL="/sites/Sitename2/$Filepath/$FileName"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Creds.UserName, $Creds.Password)
 
#Setup the contexts
$SourceCtx = New-Object Microsoft.SharePoint.Client.ClientContext($SourceSiteURL)
$SourceCtx.Credentials = $Credentials
$TargetCtx = New-Object Microsoft.SharePoint.Client.ClientContext($TargetSiteURL)
$TargetCtx.Credentials = $Credentials
 
#Get the Source File
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($SourceCtx, $SourceFileURL)
 

#Copy File to the Target location
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($TargetCtx, $TargetFileURL, $FileInfo.Stream,$True)

Anyways I keep receiving following error: Cannot send a content-body with this verb-type

How can I resolve this issue? Is there a better approach?

1 Answers

In sharepoint, we could use the MoveCopyUtil Class to copy file between sites

For example:

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SourceSiteURL)
    $Ctx.Credentials = $Credentials      
    #Copy the File
    $MoveCopyOpt = New-Object Microsoft.SharePoint.Client.MoveCopyOptions
    $Overwrite = $True
    [Microsoft.SharePoint.Client.MoveCopyUtil]::CopyFile($Ctx, $SourceFileURL, $TargetFileURL, $Overwrite, $MoveCopyOpt)
    $Ctx.ExecuteQuery()

Reference: https://www.sharepointdiary.com/2017/02/sharepoint-online-copy-file-between-document-libraries-using-powershell.html#ixzz7CSvEyjEc

Related