Wednesday, August 31, 2016

Upload files to SharePoint using Office PnP PowerShell cmdlets

Imagine you have a folder like this:

and you would like to end up with something like this in SharePoint:

If you want to programmatically upload files to a SharePoint library, there are several options available:
  1. CSOM custom code (Online and on-prem)
  2. REST API's (Online and on-prem)
  3. server-side PowerShell (on-prem)
Thanks to the work of the Office Dev PnP team there is at least one more option: The Office Dev PnP PowerShell cmdlets. And this option is beautifully simple, so I want to share it, especially since Google does not yet return any useful results showing this method.

In this post I will show you how to upload the contents of a folder to a SharePoint library using the PnP PowerShell cmdlets.

The actual cmdlet uploading the documents is Add-SPOFile (https://github.com/OfficeDev/PnP-PowerShell/blob/master/Documentation/AddSPOFile.md). The same cmdlets work with SharePoint Online and on-prem (2013 & 2016) versions. And if you want it to, the Add-SPOFile cmdlet can:

  • Check-in uploaded files automatically (-Checkout parameter)
  • Publish and approve (-Publish and -Approve parameters)

Prerequisites

First you will need the PnP PowerShell cmdlets installed. If you run Windows 10, just use the following PowerShell commands (select the version for your SharePoint environment)

  • Install-Module SharePointPnPPowerShellOnline
  • Install-Module SharePointPnPPowerShell2016
  • Install-Module SharePointPnPPowerShell2013

For any other version of Windows you can download the release packages here: https://github.com/officedev/pnp-powershell/releases

The script

The following script will do the actual uploading magic:


That's it. The script will loop through all files in the specified folder and upload the files to a corresponding path in the SharePoint library. It will even create the folders in your library in the exact same hierarchy as you have on your local disk.