This segment provides the Powershell commands to upload a single document into SharePoint Online using CSOM.
This script was tested using Powershell v5.1.19041.3570 on the desktop.
#Load The CSOM Modules
Import-Module "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Import-Module "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Set The Variables
$SPO_URL = "https://companyname.sharepoint.com/sites/sitecollection/"
$Document_Library = "MyDocLibrary"
$Source_File = "d:\MyPhoto.jpg"
$User_Name ="user@companyname.onmicrosoft.com"
$User_Password = "mypassword"
#Create The User Credentials
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User_Name, (ConvertTo-SecureString $User_Password -AsPlainText -Force))
#Establish The Context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SPO_URL)
$Context.Credentials = $Credentials
#Get the Library Information
$Library = $Context.Web.Lists.GetByTitle($Document_Library)
#Load The File Stream With The File
$FileStream = ([System.IO.FileInfo] (Get-Item $Source_File)).OpenRead()
#Get File Name from source file path
$Source_File_Name = Split-path $Source_File -leaf
#Prepare The File
$File_Creation_Info = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$File_Creation_Info.Overwrite = $true
$File_Creation_Info.ContentStream = $FileStream
$File_Creation_Info.URL = $Source_File_Name
$FileUploaded = $Library.RootFolder.Files.Add($File_Creation_Info)
#Upload The File
$Context.Load($FileUploaded)
$Context.ExecuteQuery()
#Close File Stream
$FileStream.Close()
|