SharePoint Online: Upload Files to Document Library using PowerShell
Requirement: PowerShell to upload a file to SharePoint Online document library.
In this article:
- How to upload a document to SharePoint?
- How to Upload a File to SharePoint Online Document Library using PowerShell?
- PowerShell to upload a File to SharePoint Online Document Library with metadata
- Bulk Upload All Files from a Folder to SharePoint Online Library
- PnP PowerShell to Upload File to SharePoint Online Document Library
- PnP PowerShell to Upload All Files from a Folder to SharePoint Online
- Wrapping up
How to upload a document to SharePoint?
Are you looking for a quick guide on how to upload files to SharePoint Online? This blog post will provide you with step-by-step instructions on easily uploading files to a SharePoint Online document library. We will also show you how to upload files to a SharePoint Online document library using PowerShell.
SharePoint Online allows you to create new documents or upload existing documents that are already created. So, 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.
- This opens the “Browse File” popup window where you can browse and select the 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 the information “File is available”. You may be presented with the 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 upload files. You can also upload documents by simply drag-and-drop the files into 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 files to SharePoint Online using a web browser or File Explorer, you should use a PowerShell script if you want to automatically upload files to SharePoint Online on a scheduled basis. 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 ="Salaudeen@crescent.com"
$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!"
The above script uses CSOM assemblies, which can be obtained by Downloading and installing CSOM Assemblies for SharePoint Online or Installing SharePoint Online Management Shell (CSOM is a subset of Microsoft.Online SharePoint.PowerShell module).
This PowerShell copies a single document to SharePoint Online from a local drive. If you need PowerShell to upload a file to the SharePoint document library sub-folder, refer: SharePoint Online: PowerShell to Upload File to Folder,
PowerShell to upload a File to SharePoint Online Document Library with metadata
How do you upload a file to the SharePoint library using PowerShell? How about uploading a file and setting its metadata column values with PowerShell?
#Add reference to SharePoint Online 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"
#Parameters
$SiteUrl = "https://Crescent.sharepoint.com/Sites/Marketing"
$LibraryName ="Documents"
$SourceFile="C:\Temp\SitesToCreate.csv"
#Setup Credentials to connect
$Cred = Get-Credential
Try {
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
#Get the Library
$Library = $Ctx.Web.Lists.GetByTitle($LibraryName)
#Get the file from disk
$FileStream = ([System.IO.FileInfo] (Get-Item $SourceFile)).OpenRead()
$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)
#Set metadata properties
$ListItem = $FileUploaded.ListItemAllFields
$ListItem["ReviewTimestamp"] = [System.DateTime]::Now
$ListItem.Update()
#powershell upload file to sharepoint online document library with metadata
$Ctx.Load($FileUploaded)
$Ctx.ExecuteQuery()
write-host "File has been uploaded!" -f Green
}
Catch {
write-host -f Red "Error: " $_.Exception.Message
}
Finally {
#Close file stream
$FileStream.Close()
}
This can be helpful if you need to upload a large number of files or if you want to automate the process of uploading files to a SharePoint Online document library. Alright. How about bulk uploading files to SharePoint Online using PowerShell?
Bulk 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 ="Salaudeen@crescent.com"
$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
If you need a PowerShell script to upload multiple files-folders hierarchies to SharePoint Online, use: 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 (Subfolders 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
We can also use the PnP PowerShell cmdlet Add-PnPFile to upload a file to SharePoint Online. Make sure the user credentials you supply have privileges to access the SharePoint site and set the variables like Site URL, document library name, and file path to your environment. Here is the PnP PowerShell to Copy files to the SharePoint Online document library from the local drive:
#Config Variables
$SiteURL = "https://crescent.sharepoint.com"
$SourceFilePath ="C:\Documents\Discloser Asia.docx"
$DestinationPath = "Shared Documents" #Site Relative Path of the Library
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -interactive
#powershell pnp to upload file to sharepoint online
Add-PnPFile -Path $SourceFilePath -Folder $DestinationPath
Set the $DestinationPath variable to any folder (E.g., “Shared Documents/Requirements”) in the library to upload the file to a folder in SharePoint Online. This should be either a server-relative URL or site relative URL to the target folder (E.g., If you are uploading to “https://crescent.sharepoint.com/sites/marketing/Shared Documents”, then the server relative URL is: /sites/marketing/Shared Documents, and site relative URL to the target folder is: Shared Documents – without any leading “/”). If there is a problem with the destination folder, you may get the “Add-PnPFile : Server relative urls must start with SPWeb.ServerRelativeUrl” error.
If you have MFA enabled in your tenant, You can omit the “Credentials” parameter and use -Interactive switch, so that you’ll get a popup to enter the user name and password which is two-factor authentication aware! E.g. Connect-PnPOnline -Url $SiteURL -Interactive
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 the SharePoint Online Library. Here is the PowerShell to upload a file with metadata to the SharePoint Online document library.
#Variables
$SiteURL = "https://crescent.sharepoint.com/sites/retail"
$FilesPath = "C:\Upload"
$ServerRelativePath = "/sites/retail/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
#bulk upload files to sharepoint online using powershell
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 $ServerRelativePath -Values @{"Title" = $($File.Name)}
}
This copy files to SharePoint Online. You can use these scripts to move local files to SharePoint Online using PowerShell. All the above scripts are valid for OneDrive for business sites as well. The maximum file size limit is 250 GB per file in SharePoint Online, However, to avoid connectivity timeout and bandwidth issues, you can upload larger files in chunks to SharePoint Online: How to Upload Large Files to SharePoint Online using PowerShell?
Wrapping up
In this article, we explored how PowerShell can be leveraged to automate file uploads to SharePoint Online document libraries. PowerShell’s integration with SharePoint Online and OneDrive lends itself beautifully for administrators who want reliable scripting methods to transfer content at scale. As you can see, just a few simple PowerShell commands make it easy to automate file upload tasks that could be tedious through the manual UI. By using the SharePoint PnP PowerShell module and cmdlets like Add-PnPFile, administrators and power users can efficiently transfer local files to designated library paths complete with metadata tagging. We also explored a couple of handy examples for uploading entire folders recursively and updating existing files.
Navigate to your SharePoint Online library >> Click on “Upload” from the toolbar and choose the “Folder” option. Browse and select a folder from your computer. You can also upload a folder with files and sub-folders just by dragging and dropping! PowerShell can also be used to upload a folder to SharePoint Online.
More info: Upload a folder in SharePoint Online using PowerShell
You can import files from network fileshare to SharePoint Online without any tools using PowerShell.
More info: Migrate File Share to SharePoint Online 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
SDK is free forever!
Hi Guys, How do you implement going through a proxy, in relation to the scripts above ?
Hi all, has anyone seen the error that 6 | Add-PnPFile -Path “$($File.Directory)\$($File.Name)” -Folder $Ser …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Access denied.
Thanks. Michael
Enable custom script!
Set-PnPTenantSite -Identity “Site-URL” -DenyAddAndCustomizePages:$false
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!
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?
You can use “App Passwords”, Saved credentials from a config file, Azure App ID and Password. Search this blog for more info!
I could be wrong here, but my understanding is that App Passwords are not accepted once legacy authentication is disabled.
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.”
Use the $SiteURL as https://YourDomain-my.sharepoint.com/personal/YourUserID_YourDomain_com, $ServerRelativePath = “/personal/YourUserID_YourDomain_com/Documents”
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.”
How do i upload all files from a folder on local drive to a folder in document library for on prem.
Well, You can upload files to SharePoint On-premises Document library either using CSOM script from your local machine or with Server Object Model PowerShell script from any of the SharePoint Server in your Farm!
Hello,
We have a powershell error on line 36 “$Context.ExecuteQuery() ” for uploading one file: any idea?
Thanks
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.
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 🙂
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 !
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?
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.
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!
HI, Great script. QQ: How do I upload document to a folder under a library. Thanks
Here you go: How to Upload a File to SharePoint Online Folder using PowerShell
You can try this one 🙂