SharePoint Online: Upload Files to Document Library using PowerShell

Requirement: PowerShell to upload file to SharePoint Online document library.
sharepoint online Upload Files to Document Library using PowerShell

Upload File to SharePoint Online Document Library
SharePoint Online allows you to create new documents or upload existing documents that are already created. How to upload a file to the SharePoint Online document library? Well, it's a matter of a few clicks:
  • Navigate to your SharePoint Online document library where you'd like to upload the document.
  • Click on "Upload" button from the toolbar >> Select "Files" menu item.
    sharepoint online powershell upload file to document library
  • This opens "Browse File" popup window where you can browse and select file(s)
  • Once selected and clicked on the "Open" button from the "Choose File to Upload" window, SharePoint starts uploading the documents. Once uploaded, You'll get information "File is available". You may be presented with documents pane to enter any mandatory property of the document.
You need at least the "Contribute" permission level to the document library to which you are uploading files. You can also upload documents by simply drag and drop the files to the document library or folders. Now, let's upload a file to Sharepoint Online programmatically using PowerShell.

How to Upload a File to SharePoint Online Document Library using PowerShell?
Although you can upload file to SharePoint Online using web browser or File Explorer, if you want to do it automatically, or on schedule basis you should use a PowerShell script. We can upload a document using PowerShell CSOM in SharePoint Online. Here is how to upload files to SharePoint Online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Variables for Processing
$WebUrl = "https://crescent.sharepoint.com/Sites/Sales/"
$LibraryName ="Documents"
$SourceFile="C:\SitesToCreate.csv"
$AdminName ="[email protected]"
$AdminPassword ="password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName,(ConvertTo-SecureString $AdminPassword -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl) 
$Context.Credentials = $Credentials

#Get the Library
$Library =  $Context.Web.Lists.GetByTitle($LibraryName)

#Get the file from disk
$FileStream = ([System.IO.FileInfo] (Get-Item $SourceFile)).OpenRead()
#Get File Name from source file path
$SourceFileName = Split-path $SourceFile -leaf
  
#sharepoint online upload file powershell
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $SourceFileName
$FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)
 
#powershell upload single file to sharepoint online
$Context.Load($FileUploaded) 
$Context.ExecuteQuery() 

#Close file stream
$FileStream.Close()
 
write-host "File has been uploaded!" 
This PowerShell copies a single document to SharePoint Online from local drive. If you need PowerShell to upload file to SharePoint Online document library sub-folder, refer: SharePoint Online: PowerShell to Upload File to Folder, Alright. How about bulk upload files to SharePoint Online using PowerShell?

Upload All Files from a Folder to SharePoint online Library:
How to upload multiple files to SharePoint Online? Sure, let's upload all files from a local folder to the SharePoint Online library using PowerShell.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
### Variables for Processing
$WebUrl = "https://crescent.sharepoint.com/Sites/Sales/"
$LibraryName ="Documents"
$SourceFolder="C:\Documents"
$UserName ="[email protected]"
$Password ="password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl) 
$Context.Credentials = $Credentials

#Get the Library
$Library =  $Context.Web.Lists.GetByTitle($LibraryName)

#upload each file from the directory
Foreach ($File in  (dir $SourceFolder -File))
{
    #Get the file from disk
    $FileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
  
    #Upload the File to SharePoint Library
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $File
    $FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)
 
    #powershell to upload files to sharepoint online
    $Context.Load($FileUploaded) 
    $Context.ExecuteQuery() 

    #Close file stream
    $FileStream.Close()

    write-host "File: $($File) has been uploaded!"
} 
This uploads files to SharePoint Online using PowerShell. If you need to set the metadata of a file, use: PowerShell to Update metadata of a File in SharePoint Online Document Library
sharepoint online upload document powershell
If you need a PowerShell script to upload multiple files-folders hierarchies to SharePoint Online: Upload a Folder to SharePoint Online using PowerShell, This can be used to upload a folder to SharePoint Online as well! How about uploading a folder with its contents (Sub-folders and Files) to SharePoint Online? Here is the PnP PowerShell  Upload Multiple Files to SharePoint Online using PowerShell

PnP PowerShell to Upload File to SharePoint Online Document Library
Here is the PnP PowerShell to Copy file to SharePoint Online document library from local drive.
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com"
$SourceFilePath ="C:\Documents\Discloser Asia.docx"
$DestinationPath = "/Shared Documents" #Relative Path of the Library
 
#Get Credentials to connect
$Cred = Get-Credential
 
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred
     
#powershell pnp to upload file to sharepoint online
Add-PnPFile -Path $SourceFilePath -Folder $DestinationPath

PnP PowerShell to Upload All Files from a Folder to SharePoint Online:
Let's use PnP PowerShell to bulk copy all files from a local folder to SharePoint Online Library. Here is the PowerShell to upload file to SharePoint Online document library with metadata.
#Variables
$SiteURL = "https://crescenttech.sharepoint.com"
$FilesPath = "C:\Upload"
$SiteRelativePath = "/Shared Documents/"

#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get All Files from a Local Folder
$Files = Get-ChildItem -Path $FilesPath -Force -Recurse

#Upload All files from the directory
ForEach ($File in $Files)
{
    Write-host "Uploading $($File.Directory)\$($File.Name)"
 
    #upload a file to sharepoint online using powershell - Upload File and Set Metadata
    Add-PnPFile -Path "$($File.Directory)\$($File.Name)" -Folder $SiteRelativePath -Values @{"Title" = $($File.Name)}
}
This copies files to SharePoint Online with PowerShell. If you want to upload larger files to SharePoint Online, use: How to Upload Large Files to SharePoint Online using PowerShell?

7 comments:

  1. HI, Great script. QQ: How do I upload document to a folder under a library. Thanks

    ReplyDelete
    Replies
    1. You can try this one :)
      #Load SharePoint CSOM Assemblies
      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"

      #Set parameter values for site
      $SiteURL="https://crescent.sharepoint.com/Sites/Sales/"

      #Set parameter values for Library
      $LibraryName="Documents"

      #Set parameter values for Sub Directory under Documents Library
      $upload_location="/Folder2/Folder1/"

      #Set parameter values for Destination Directory
      $Sourcefile="C:\download"

      #Set parameter values for File to download
      #$File="testcsv2.csv"

      #Setup Credentials to connect
      $global:AdminName ="user"
      $global:AdminPassword ="password"



      Function Get-Context($SiteURL){

      #Setup Credentials to connect
      $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($global:AdminName,(ConvertTo-SecureString $global:AdminPassword -AsPlainText -Force))

      #Setup the context
      $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
      $Ctx.Credentials = $Credentials

      #Rturn the value ctx
      return $ctx

      }



      # Fuction for uploading the file
      Function Uploading-FilesFromLibrary()
      {
      #check parameter for SiteURL,LibraryName,TargetFolder,File and Subdir
      param
      (
      [Parameter(Mandatory=$true)] [string] $SiteURL,
      [Parameter(Mandatory=$true)] [string] $LibraryName,
      [Parameter(Mandatory=$true)] [string] $Sourcefile,
      [Parameter(Mandatory=$true)] [string] $upload_location
      )

      Try {

      #Setup the context
      $ctx = Get-Context -SiteURL $SiteURL


      #Retrieve list
      $List = $ctx.Web.Lists.GetByTitle($LibraryName)
      $ctx.Load($List.RootFolder)
      $ctx.ExecuteQuery()


      $TargetFolder = $ctx.Web.GetFolderByServerRelativeUrl($List.RootFolder.ServerRelativeUrl + $upload_location)


      #Upload file
      Foreach ($File in (dir $Sourcefile -File))
      {
      $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 = $TargetFolder.Files.Add($FileCreationInfo)
      $ctx.Load($TargetFolder)
      $ctx.ExecuteQuery()

      Write-host -f Green "'$File' from Library '$Sourcefile' Uploaded to Folder '$upload_location' Successfully!" $_.Exception.Message

      }

      #Write-host -f Green "'$File' from Library '$Sourcefile' Uploaded to Folder '$upload_location' Successfully!" $_.Exception.Message

      }
      Catch {
      write-host -f Red "Error Uploading Files from Library!" $_.Exception.Message
      }
      }

      #Call the function to Uploading file
      Uploading-FilesFromLibrary -SiteURL $SiteURL -LibraryName $LibraryName -Sourcefile $Sourcefile -upload_location $upload_location

      Delete
  2. Very useful information, thank you. Would like to add the logic to recreate the exact sub-folder structure in documents up to sharepointonline library. Think I need to make two passes, one to create all the sub-folders and sub-sub-folders, etc. and then one to copy the files in to all the proper folders. Don't want them all in the root library folder. Need them in same folder locations as they are on the disk.

    ReplyDelete
    Replies
    1. Sure, Use this script: PowerShell script to Import from File share to SharePoint Online, This can be used to import from local folder to SharePoint Online as well!

      Delete
  3. I had crazy problem with a library with spaces in the name. It was between quotes like "this is my library" but that gave me a crazy error message in powershell. >>> "Identity client Runtime Library (IDCRL) could not look up the real information for federated sign-in" If you google this message you get so many different hits but nothing worked. So i just tried to upload to the default "Documents" folder in Sharepoint Online and it worked perfectly. Then the Sharepoint Admin removed the spaces in the original library name and then that folder worked too. So...dont use spaces in Library names ! Thank you very much for the script, maybe you should write a hint in the script regarding that "no spaces" problem. This will save many hours in the future i think. Thanks again my friend !

    ReplyDelete
    Replies
    1. That's sounds Odd! I'm able to upload to libraries that contains space with in CSOM and PnP! Are you missing double quotes that wraps Library name by any chance?

      Delete

Please Login and comment to get your questions answered!

Powered by Blogger.