FromTheField

Real world experiences of SharePoint PFE and CTS engineers from Microsoft UK

Office 365 - PowerShell Script to Upload Files to a Document Library using CSOM

Office 365 - PowerShell Script to Upload Files to a Document Library using CSOM

  • Comments 15
  • Likes

UPDATE: The script now supports uploading files larger than 2MB.

Another PowerShell sample script for you. This one uploads all files within a specified local directory to a Document Library within a Site in an O365 tenant.

All you need to run this script is an O365 tenant, the SharePoint client components SDK installed on the machine running the script - http://www.microsoft.com/en-us/download/details.aspx?id=35585 and to update the $User, $SiteURL, $DocLibName (name of the destination Document library) and $Folder (path to the local folder containing the files to upload) variables. When the script is executed it will prompt for the password of the user specific in the $User variable.

One thing to point out is that CSOM has a maximum upload size of 2MB.

#Specify tenant admin and site URL
$User = "admin@tenant.onmicrosoft.com"
$SiteURL = "https://tenant.sharepoint.com/sites/site"
$Folder = "C:\FilesToUpload"
$DocLibName = "DocLib"

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()

#Upload file
Foreach ($File in (dir $Folder))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}


Brendan Griffin

Comments
  • Thanks Brendan - do you know of a similar routine that would let one create a new Document set and upload documents into it?

  • There is an article here - http://www.c-sharpcorner.com/Blogs/12139/how-to-create-document-set-using-csom-in-sharepoint-2013.aspx but it's using C#, should be easy enough to convert to PS. I may even do a Blog post on it :)

  • Great, thanks. One more question- in regards to the 2MB limit- the Answer on the post at http://social.msdn.microsoft.com/Forums/sharepoint/en-US/deac7cb7-c677-47b0-acdc-c56b32dfaac8/uploading-bigger-files-using-csom?forum=sharepointdevelopment seems to demonstrate the streaming method necessary to overcome the 2MB limit. Do you know if that's possible to recreate the streaming method in PowerShell as opposed to the C# example provided?

  • I have updated the script to support files larger than 2MB.

  • Hi, brilliant work, do you know if its possible to create a script to download/ copy all documents from an O365 site collection to a local drive?

    Thanks

  • Yes, I'm actually working on something very similar at the moment. Will post once it's ready.

  • Love the script.
    Wondering how to tweak it to upload meta data with the files also?
    Thanks.

  • Hi, is it possible to share the similar script for download?

  • I am not sure why I am only getting the below error while executing this code. Please help me to fix.

    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:24 char:1
    + $List = $Context.Web.Lists.GetByTitle($DocLibName)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:25 char:1
    + $Context.Load($List)
    + ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:26 char:1
    + $Context.ExecuteQuery()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    2
    True
    3
    True
    2
    Success
    Close
    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:63 char:1
    + $Upload = $List.RootFolder.Files.Add($FileCreationInfo)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:64 char:1
    + $Context.Load($Upload)
    + ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At D:\SP2013 Online\OnlineWorks\get site information\test.ps1:65 char:1
    + $Context.ExecuteQuery()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

  • Looks as though it is having an issue connecting to the list specified in the $DocLibName variable, may be worth checking this to ensure that the library is present.

  • Trying to move a file inside sharepoint from folder A to folder A\Done (After processing). Do you have any sample script i can use to move a file?

    Thanks

  • I am unable to get this script to work- i get an error in powershell. I made a copy of the directory that I need to upload and gave "full access" NTFS permission to "everyone" just for the sake of testing and ruling out NTFS Perms... any suggestions?

    New-Object : Exception calling ".ctor" with "2" argument(s): "Access to the path 'E:\files\SALES_DOCUMENTS' is denied."
    At line:25 char:15
    + $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

    Exception calling "Add" with "1" argument(s): "Cannot access a closed file."
    At line:30 char:1
    + $Upload = $List.RootFolder.Files.Add($FileCreationInfo)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ObjectDisposedException

    Exception calling "Load" with "1" argument(s): "The object is used in the context different from the one associated with the object."
    At line:31 char:1
    + $Context.Load($Upload)
    + ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

    Exception calling "ExecuteQuery" with "0" argument(s): "Invalid request."
    At line:32 char:1
    + $Context.ExecuteQuery()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServerException

  • Hi, Can you please provide the script to upload more than 2MB file size, I am looking up to 2GB file size upload. Please send script to sharepointind@gmail.com

    Thanks for your help.

  • Hi,
    I was wondering if you are able to create folders in the same way?

  • Office 365 - PowerShell Script to Upload Files to a Document Library using CSOM
    hassan sayed issa

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment