Upload Files to SharePoint Library Remotely using Client-Side Object Model (CSOM) and PowerShell
Requirement: Upload files to a 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 the 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 = "https://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)
$Context.Load($List)
$Context.ExecuteQuery()
#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)
$Context.Load($FileUploaded)
$Context.ExecuteQuery()
#Set Metadata
$properties = $FileUploaded.ListItemAllFields;
$context.Load($properties)
$properties["Category"]="Reports"
$properties.Update()
$context.ExecuteQuery()
#Close file stream
$FileStream.Close()
Important: Make sure you have SharePoint 2013 Client Components SDK installed in your client machine before running this script!
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.
You can provide the user name & password in the script. Just check the line below:
#connect using user account/password