Upload Files to SharePoint Library Remotely using Client Object Model (CSOM) and PowerShell

Requirement: Upload files to SharePoint document library remotely.

PowerShell Script to Upload a File to SharePoint Library using Client Object Model:
We can upload files to SharePoint Online or SharePoint on-premises document libraries remotely using PowerShell and client side object model (CSOM).
#Load SharePoint CSOM Assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null

##Variables for Processing
$SiteUrl = "http://mgmt.crescent.com/"
$LibraryName="Proposal Documents"
$SourceFile ="D:\Reports\MonthlyRpt.csv"

#Setup Credentials to connect
$Credentials = [System.Net.CredentialCache]::DefaultCredentials  #Current User Credentials
#connect using user account/password
#$Credentials = New-Object System.Net.NetworkCredential($UserName, (ConvertTo-SecureString $Password -AsPlainText -Force))
#For Office 365, Use:
#$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))

#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials
$web = $Context.Web

#Get the Library
$List = $web.Lists.GetByTitle($LibraryName)
#Get File Name from source file path
$SourceFileName = Split-path $SourceFile -leaf 

#Get Source file contents
$FileStream = ([System.IO.FileInfo] (Get-Item $SourceFile)).OpenRead()

#Upload to SharePoint
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $SourceFileName
$FileUploaded = $List.RootFolder.Files.Add($FileCreationInfo)

#Set Metadata
$properties = $FileUploaded.ListItemAllFields;
#Close file stream
Important: Make sure you have SharePoint 2013 Client Components SDK installed in your client machine prior running this script!


  1. Where or how do you enter the username and password for the credentials part?

    The script looks like something I could really use, but I need to be able to schedule it, so I can't enter the username/password every time it runs.

    1. You can provide the user name & password in the script. Just check the line below:
      #connect using user account/password


Please Login and comment to get your questions answered!

Powered by Blogger.