SharePoint Online: Upload File to Sub-Folder using PowerShell

Requirement: SharePoint Online PowerShell to Upload File to Folder

How to upload a File to Folder in SharePoint Online?

Folders are still a great way to organize your files and keep them all in one place. In this blog post, I will show you how to use PowerShell to upload a file to a folder in a SharePoint Online site. This is handy if you need to automate the process of uploading files to your SharePoint site.

You can upload a file to a specific folder in a SharePoint Online document library by:

  • Navigate to the folder through the web browser
  • Click on the “Upload” button in the toolbar of any document library, choose “Files” and then browse your computer for files that are stored locally.
  • Find the desired file, select it, click Open, then the upload will start.
upload file to sharepoint online folder powershell

Once the upload process is complete, the progress bar at the top will reach 100%.

PowerShell to Upload File to SharePoint Online Sub-Folder

PowerShell is an amazingly powerful language that can be used to automate many of your IT tasks. One of the most common tasks you might want to automate with PowerShell is uploading files to the SharePoint Online document library subfolder.

Often you may need to upload a file to SharePoint Online, but it is the same process every time! So, let us use PowerShell to automate it. Here is the PowerShell to upload file to SharePoint Online Document library subfolder:

#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"

#Set parameter values
$SiteURL="https://crescent.sharepoint.com/sites/marketing"
$SourceFilePath="C:\Users\salaudeen\Desktop\Project Documents\Discloser Asia.doc"
$TargetFolderRelativeURL ="/sites/Marketing/Shared Documents/2018/Active"

#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
      
    #Get the Target Folder to upload
    $Web = $Ctx.Web
    $Ctx.Load($Web)
    $TargetFolder = $Web.GetFolderByServerRelativeUrl($TargetFolderRelativeURL)
    $Ctx.Load($TargetFolder)
    $Ctx.ExecuteQuery() 

    #Get the source file from disk
    $FileStream = ([System.IO.FileInfo] (Get-Item $SourceFilePath)).OpenRead()
    #Get File Name from source file path
    $SourceFileName = Split-path $SourceFilePath -leaf   
    $TargetFileURL = $TargetFolderRelativeURL+"/"+$SourceFileName

    #Upload the File to SharePoint Library Folder
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $TargetFileURL
    $FileUploaded = $TargetFolder.Files.Add($FileCreationInfo)  
    $Ctx.ExecuteQuery()  

    #Close file stream
    $FileStream.Close()
    Write-host "File '$TargetFileURL' Uploaded Successfully!" -ForegroundColor Green
}
catch {
    write-host "Error Uploading File to Folder: $($_.Exception.Message)" -foregroundcolor Red
}

This PowerShell uploads files to the SharePoint Online document library sub-folder.

Upload File to SharePoint Online Folder using PnP PowerShell

To upload a file to a folder in SharePoint Online document library using PnP PowerShell, use:

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/retail"
$SourceFilePath ="C:\Documents\SRS.Docx"
$DestinationFolderPath = "/sites/retail/Shared Documents/2018" #Server Relative URL

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    
    #Upload File to Folder
    Add-PnPFile -Path $SourceFilePath -Folder $DestinationFolderPath -ErrorAction Stop
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

The Add-PnPFile cmdlet also supports these parameters: NewFileName, Checkout, Approve, Publish, ContentType, and Values. If you need to upload all files and folders from a local drive to SharePoint Online using PowerShell, use: SharePoint Online: Upload All Files & Sub-Folders using PowerShell

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

12 thoughts on “SharePoint Online: Upload File to Sub-Folder using PowerShell

  • I have created script to upload the file into SP online. I could able to create subfolder. but unable to upload the file anywhere and returned error which I couldn’t figured out. I have followed the first code in above to upload. The below code returned the error.
    $FileUploaded = $TargetFolder.Files.Add($FileCreationInfo)

    Cannot convert argument “parameters”, with value: “Microsoft.SharePoint.Client.FileCreationInformation”, for “Add” to type “Microsoft.SharePoint.Client.FileCreationInformation”:
    “Cannot convert the “Microsoft.SharePoint.Client.FileCreationInformation” value of type “Microsoft.SharePoint.Client.FileCreationInformation” to type
    “Microsoft.SharePoint.Client.FileCreationInformation”.”

    Reply
  • This doesn’t work with Modern Authentication.

    Reply
  • The first script gives me the error “File Not Found.” eventhough its there. Am i missing something?

    Reply
    • You’ll get ‘Error Uploading File to Folder: Exception calling “ExecuteQuery” with “0” argument(s): “File Not Found.”‘ error, when the folder path specified in $TargetFolderRelativeURL doesn’t exist. It should be the Server relative path of the folder you wish to upload the file.

      Reply
      • Could you explain why “sites/marketing” (one with capitalized M) is in $SiteURL and $TargetFolderRelativeURL? thanks in advance

        Reply
  • How do you modify this to upload all files, sub folders to a sub folder in sharepoint? Ex… How to upload c:\source\*.* to sharepoint sub folder at /sites/myteam/shared documents/general/subfolder

    Reply
  • I have created new script to upload files in subfolder in sharepoint

    #Specify tenant admin and site URL
    $User = "your user_name"
    $SiteURL = "https://*****.sharepoint.com"
    
    #local pc folder
    $Folder = "C:\dest"
    
    $DocLibName = "Documents"
    
    #folder of sharepoint where you want to copy the file or folder
    $FolderName = "Data_Center/Backups/HRMS/"
    
    #install sharepoint sdk on your machine and give path of this in below code
    #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\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
    
    #your password
    $Password = "********"  | ConvertTo-SecureString -AsPlainText -Force
    
    #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.RootFolder)
    $Context.ExecuteQuery()
    
    #Retrieve list
    $List = $Context.Web.Lists.GetByTitle($DocLibName)
    $Context.Load($List.RootFolder)
    $Context.ExecuteQuery()
    
    $TargetFolder = $Context.Web.GetFolderByServerRelativeUrl($List.RootFolder.ServerRelativeUrl + "/" + $FolderName);
    
    
    #Upload file(s)
    Foreach ($File in (dir $Folder -File))
    {
        $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
        $FileCreationInfo.Overwrite = $true
        $FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
        $FileCreationInfo.URL = $File.Name
        $UploadFile = $TargetFolder.Files.Add($FileCreationInfo)
        $Context.Load($UploadFile)
        $Context.ExecuteQuery()
    }
    
    Reply
    • Hi,

      Why do you have “Retrieve List” listed twice above? Is it a typo?

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

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

      Reply

Leave a Reply

Your email address will not be published.