How to upload a file to a library of SharePoint Online Using Client Object Model

Introduction

This script will help users to upload a file to a library or OneDrive for Business of SharePoint Online.

Scenarios

This script is to help users to upload a file to a library or OneDrive for Business of SharePoint Online using Client Object Model.

Prerequisites

This script requires SharePoint Server 2013 Client Components SDK. Please download and install the package from Microsoft Download Center. This script cannot work correctly without this package. This script requires the Remote Authentication supported by the following demo. Please build this sample and refer to the ClaimsAuth.dll to this script.

Script

You can use this script in the following way.

1. Open Windows PowerShell.

2. Type the one command< Script Path> at the Windows PowerShell Console.
For example, type C:\Script\
UploadFileInOneDriveofSPO.ps1

Here are some code snippets for your reference.

PowerShell
Edit|Remove
$filestream = [IO.file]::ReadAllBytes($filePath+"\"+$FileName)
    $fields=@()
    $results = $null 
    $destinationurl = $LibraryURL + "/" + $fileName
    $ret = $service.CopyIntoItems(" ",$destinationurl,$fields,$filestream,[ref]$results)

Examples

 Example: Upload a local file to OneDrive for Business

The sample is shown below
 
UploadFileInOneDriveofSPO.ps1 -DllPath "c:\ClaimsAuth.dll" –filePath "c:\" –FileName "Upload.txt" -LibraryURL "https://user-my.sharepoint.com/personal/user_contoso_onmicrosoft_com/Documents"

Command Screenshot:

Result Screenshot:  

Additional Resources

Technical Resources: 

Windows PowerShell Advanced Function
Connecting to SharePoint Online Web Services

 

Microsoft All-In-One Script Framework is an automation script sample library for IT Professionals. The key value that All-In-One Script Framework is trying to deliver is Scenario-Focused Script Samples driven by IT Pros' real-world pains and needs. The team is monitoring all TechNet forums, IT Pros' support calls to Microsoft, and script requests submitted to TechNet Script Repository. We collect frequently asked IT scenarios, and create script samples to automate the tasks and save some time for IT Pros. The team of All-In-One Script Framework sincerely hope that these customer-driven automation script samples can help our IT community in this script-centric move.