Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

24 thoughts on “SharePoint Online: Upload Files to Document Library using PowerShell

  • Hi Salaudeen
    Thanks for the solution to upload file , which help us to automate the report upload. Could you please confirm that the given SDK is free and I can use. Some where I seen its for 90 days. I am not sure whether I read correctly. Could you please confirm the given SDK is free or is it valid only for 90 days.
    https://www.microsoft.com/en-us/download/details.aspx?id=42038

    Reply
  • Hi Guys, How do you implement going through a proxy, in relation to the scripts above ?

    Reply
  • Hi all, has anyone seen the error that 6 | Add-PnPFile -Path “$($File.Directory)\$($File.Name)” -Folder $Ser …
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | Access denied.

    Thanks. Michael

    Reply
    • Enable custom script!
      Set-PnPTenantSite -Identity “Site-URL” -DenyAddAndCustomizePages:$false

      Reply
  • Hi Salaudeen,
    The script to upload a File to SharePoint Online Document Library with metadata is brilliant. It works well on a Test Tenant. However I need to run it against a Tenant that has switched to modern Authentication.

    I’ve tried https://www.sharepointdiary.com/2019/08/connect-sharepoint-online-powershell-using-mfa.html but I cant get an App Password. I can log onto the SP site via a browser and not using MFA. How the script be changed? Many thanks!

    Reply
  • Is there anyway to handle more modern auth mechanisms for this? Two different scenarios:

    1. If I have conditional access policies setup for most of my users to use MFA to login to o365, how would I accomplish a powershell upload process when the system demands MFA?

    2. What about if I wanted to run something like this as a scheduled task to run without user intervention? Say I wanted to fire of the above powershell from a server at 1:00 AM every day? How would you tackle the authentication piece when MFA is required?

    Reply
    • You can use “App Passwords”, Saved credentials from a config file, Azure App ID and Password. Search this blog for more info!

      Reply
      • I could be wrong here, but my understanding is that App Passwords are not accepted once legacy authentication is disabled.

        Reply
  • I have trouble using the “Bulk Upload All Files from a Folder to SharePoint Online Library” Script with one Drive Business. I dont know what to enter in $WebUrl and Libary $Name to target the shared folder….

    Getting Error:
    Line |
    37 | $Context.ExecuteQuery()
    | ~~~~~~~~~~~~~~~~~~~~~~~
    | Exception calling “ExecuteQuery” with “0” argument(s): “The remote server returned an error: (400) Bad Request.”

    Reply
    • Use the $SiteURL as https://YourDomain-my.sharepoint.com/personal/YourUserID_YourDomain_com, $ServerRelativePath = “/personal/YourUserID_YourDomain_com/Documents”

      Reply
  • What do you do if a guest user with write permission in SP to run this script remotely and upload? For same Org users it work, it guest (external user) there are security limitation.
    “The Login server cannot issue the requested compact encrypted ticket because a Data Encryption Key (DEK) has not been uploaded to the site.”

    Reply
  • How do i upload all files from a folder on local drive to a folder in document library for on prem.

    Reply
  • Hello,
    We have a powershell error on line 36 “$Context.ExecuteQuery() ” for uploading one file: any idea?
    Thanks

    Reply
  • Thank you very much Rajack, I really appreciate it. I was already very tired of looking for information to be able to upload files through Programming Languages, “A full month”, “I did not succeed because of issues on my side and customer security issues.” I found your blog and without having knowledge of PowerShell, I managed to complement it with all the examples that you expose and I managed to make a script that allows me to upload files in bulk, in any folder and with only the url of the sharepoint site along with the access variables . Thanks very much buddy.

    Reply
  • Hi is there anyway to get the details for the uploaded files in a log file ? like the last modified date and time, upload date, name of the respective file, and other things. If yes please guide me a little towards the same, as i am completely new to powershell and sharepoint, but after bulk uploading files successfully using this article,(it was really great,thanks for the article). But i suppose if we would have been able to keep track of all the files than it would be much more useful to the user.
    Any help is appreciated.
    Thanks 🙂

    Reply
  • 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 !

    Reply
    • 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?

      Reply
  • 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.

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

    Reply
    • 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
      }
      
      # Function 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
      
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *