Uploading files to a specific folder within a SharePoint document library using CSOM + PowerShell

Uploading files to a specific folder within a SharePoint document library using Client Side Object Model + PowerShell….

# Source folder, for example the display templates folder within the masterpage gallery
$sourceFolder = "_catalogs/masterpage/Display%20Templates/Content%20Web%20Parts"

#file path, location of the file to upload
£filePath = "C:\Projects\POC\Upload\Control_Default.html"

$sourceFolder = $ctx.Web.GetFolderByServerRelativeUrl($relativeFolderLocation);
$ctx.Load($sourceFolder)
$ctx.ExecuteQuery()

$filePath = Get-ChildItem $filePath	
$fileBytes = [System.IO.File]::ReadAllBytes($filePath.FullName)

$fileinfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$fileinfo.Content = $fileBytes
$fileinfo.Url = $relativeFolderLocation + "/" + $filePath.Name
$fileinfo.Overwrite = $true

$ctx.Load($sourceFolder.Files.Add($fileinfo))
$ctx.ExecuteQuery()
Add-LogMessage -message "Adding file to document library"
Advertisements