Powershell Script to Upload Files to Dropbox
In this PowerShell SharePoint tutorial, we will discuss how to upload files to SharePoint using PowerShell.
Today in this commodity I would like to advance the script to upload the documents from user'southward machine likewise called remote information upload. Since we can't become the object of the SharePoint site in a PowerShell script I am using the WebClient object. WebClient is one of the ways to get the object for a site.
The requirement still remains the same equally final time that the user wants to drift all the documents from his network drive to the SharePoint document library as part of data migration. Since there are millions of files in the user network bulldoze, I can't ask the user to upload all his files one past one nor with the explorer view. Copying files manually will have quite a skillful fourth dimension of time.
The beneath PowerShell script uploads all the user documents to document library. This script I can run request stop-user to execute on his local car equally and when he/she require. Another way is that I can run on behalf of the business organisation user on my auto without doing a remote to the SharePoint server.
Let us meet, how to upload files to SharePoint using PowerShell remotely.
The PowerShell script is as follows:
# This Powershell script is to uplaod the files to a sharepoint certificate library REMOTELY with user Credentails function UploadDocuments($destination, $File,$userID, $securePasssword) { try { # Since we're doing this remotely, we demand to authenticate $credentials = New-Object System.Management.Automation.PSCredential ($userID, $securePasssword) # Upload the file $webclient = New-Object System.Cyberspace.WebClient $webclient.Credentials = $credentials $webclient.UploadFile($destination + "/" + $File.Proper name, "PUT", $File.FullName) } catch { Write-Host "Fault:: $($_.Exception.Bulletin)" -foregroundcolor red -BackgroundColor Yellow } } # Prepare the variables $destination = "<<Document Library URL >>" $fileDirectory = "C:\Krishna\PowerShell Scripts\PS Testing\T\*.*" $userName = Read-Host "Enter User-ID (domain\userID):: " $securePasssword = Read-Host "Please enter the password for user $($userName) :: " -AsSecureString #Reading through the folder foreach($fileName in Get-ChildItem $fileDirectory) { UploadDocuments -destination $destination -File $fileName -userID $userName -securePasssword $securePasssword Write-Host "Uploaded File=" $fileName.Name } Write-Host "Script executed Successfully"
Note:
Whoever is running script should have contribute access to the SharePoint document library.
Let u.s. walk through the script:
I am reading password with the below line of code in PowerShell command prompt:
$securePasssword = Read-Host "Please enter the countersign:" -AsSecureString
The below line is to associate the user name and password which will exist used while creating object to the SharePoint site.
$credentials = New-Object System.Management.Automation.PSCredential ("<<Domain\userID>", $securePasssword)
We are making call to get the object to SharePoint using provided user credentials and WebClient.
# Upload the file $webclient = New-Object Arrangement.Net.WebClient $webclient.Credentials = $credentials $webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)
Uploading the file to SharePoint certificate library:
$webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)
In the above line destination is the proper noun of the certificate library
- $File.Name is the name of the file to be created as in certificate library
- $File.FullName is the path of the file from where information technology needs to exist uploaded from
How to run this PowerShell script?
Delight follow the below steps to execute the PowerShell script:
- Save the above script as "UploadDocuments_With Credentials.ps1"
- Open PowerShell Command let as administrator
- Navigate to the folder where you lot relieve the PS1 script
- Execute the script by typing ".\UploadDocuments_With Credentials.ps1" every bit shown in the below screenshot.

- This script has will upload all the file in "C:\Temp\PS Testing\T" folder as mentioned in the code.
Output:
Files uploaded to SharePoint Library:
In the output you can see the uploaded user name.

Note: This script will not piece of work for SharePoint online sites.
Read: PowerShell SharePoint list operations and PowerShell SharePoint site drove example.
Here we will see how to upload documents to SharePoint Document Library using PowerShell Remotely with the default account.
At present, I would like to accelerate the script to upload the documents from user'south machine also called remote data upload without providing user credentials. Since we are not providing user credentials I am using "Invoke-WebRequest". Using this script user can upload the documents to the library merely it will upload the document with "System ACCOUNT" as user name.
The requirement withal remains the same as last time that the user wants to drift all the documents from his network bulldoze to the SharePoint certificate library as part of data migration. Since there are millions of files in the user network drive, I can't ask the user to upload all his files one by one nor with the explorer view. Copying files manually volition take quite a good time of time.
The below PowerShell script uploads all the user documents to the document library. This script I tin run request end-user to execute on his local machine as and when he/she require. Another way is that I tin can run on behalf of the business organisation user on my machine without doing a remote to the SharePoint server.
The PowerShell script is as follows:
# This script is to upload the documents from local folder to Sharepoint Document library without user stamp role UploadDocuments($destination, $File) { attempt { #Rading file data with IO stream $content = [Organisation.IO.File]::ReadAllBytes($File) #appending file name with the destination document library path $objFile = $destination+$File.Proper noun #This will upload the file in certificate library with "System Account" as user proper name Invoke-WebRequest -Uri $objFile -Body $content -Method PUT -UseDefaultCredentials } grab { Write-Host "Error:: $($_.Exception.Message)" -foregroundcolor ruddy -BackgroundColor Yellow } } # Set up the variables $destination = "<< Site URL >>" $fileDirectory = "C:\Krishna\PowerShell Scripts\PS Testing\*.*" #Reading through the document library foreach($fileName in Get-ChildItem $fileDirectory) { #Calling method to upload the files from local folder UploadDocuments -destination $destination -File $fileName #Press file name in Powershell control prompt Write-Output "Uploaded File" $fileName } Write-Host "Script executed Successfully" #Annotation: This script upload the files with System account. Notwithstanding who ever is executing the script must have # contribute access on document library.
Annotation:
Whoever is running script should have contributed access to the certificate library.
Since I take added comments for each and every line the code is self-explanatory.
How to execute this PowerShell script:
Please follow the below steps to execute the PowerShell script:
- Relieve the above script equally "UploadDocuments_With out Credentials.ps1"
- Open PowerShell Command let as administrator
- Navigate to the folder where you save the PS1 script
- Execute the script by typing ".\UploadDocuments_With out Credentials.ps1" equally shown in the below screenshot.

- This script has volition upload all the file in "C:\Temp\PS Testing\T" folder as mentioned in the code.
Output:
Files uploaded to SharePoint Library:
In the output you lot can see the uploaded user name.

Note: This script will not work for SharePoint online sites.
Read: 40 Useful PowerShell SharePoint Commands.
Let u.s.a. see, how to upload files to sharepoint online using powershell.
I would like to speak about the process to upload the documents to the SharePoint Online site from your local environment.
However, the requirement yet remains the same as last time that user wants to migrate all the documents from his network / local drive to SharePoint online document library equally part data migration.
Since at that place are millions of files in the user'south drive, I can't ask the user to upload all his files one by 1 nor with the explorer view. Copying files manually volition have quite a proficient time of fourth dimension.
The below PowerShell script uploads all the user documents to SharePoint Online document library. This script I can run request end-user to execute on his local motorcar equally and when he/she require. Some other way is that I tin run on behalf of the concern user on my motorcar seamlessly.
Below is the PowerShell script to upload documents to the SharePoint Online document library remotely.
endeavour { #Specify tenant admin and site URL and user name $User = "[email protected]" $SiteURL = https://onlysharepoint2013.sharepoint.com/sites/krishna #Specify Local folder proper noun where the files are to exist uploaded $Folder = "G:\KVN Articles\PS Testing\Files" $DocLibName = "Finance" $startedTime = Get-Date Write-Host "Time Started = " $startedTime #Add together references to SharePoint client assemblies and authenticate to Function 365 site – required for CSOM Add-Blazon -Path "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.SharePoint.Customer\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Customer.dll" Add-Type -Path "C:\Windows\Microsoft.Internet\assembly\GAC_MSIL\Microsoft.SharePoint.Customer.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll" #Reading Password from PowerShell Control line $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 #Creating Object to Document Library $Listing = $Context.Spider web.Lists.GetByTitle($DocLibName) $Context.Load($Listing) $Context.ExecuteQuery() #Reading through the local folder for files Foreach ($File in (dir $Binder -File)) { #Reading File data using IO stream object $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open) $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation $FileCreationInfo.Overwrite = $truthful $FileCreationInfo.ContentStream = $FileStream $FileCreationInfo.URL = $File #Uploading file to document library $Upload = $List.RootFolder.Files.Add together($FileCreationInfo) $Context.Load($Upload) $Context.ExecuteQuery() Write-Host "Uploaded File=" $File.Name } $completedTime = Get-Date Write-Host "Time Completed = " $completedTime Write-Host "Script Excecuted Successfully !!!" } take hold of { write-host "Error: $($_.Exception.Bulletin)" -foregroundcolor red }
I strongly believe that the script is self-explanatory as I take added comments for most of the lines.
Annotation:
To execute this script user must install the SharePoint client components SDK on his/her auto.
Steps to exist followed to ensure the smooth execution:
Ensure that SharePoint Customer components SDK installed on the user automobile
Microsoft.SharePoint.Customer.dll and Microsoft.SharePoint.Customer.Runtime.dll paths mentioned in the script are the same as the user's machine
Open PowerShell command-permit with Run as Administrator
Check the "execution policies" for PowerShell in user machine past executing below command in PowerShell command permit
Get-ExecutionPolicy -Listing
The above command will get all the existing policies of the user by and large the output volition be equally follows:
Scope | ExecutionPolicy |
MachinePolicy | Undefined |
UserPolicy | Undefined |
Process | Undefined |
CurrentUser | Undefined |
LocalMachine | Undefined |
We need to change the execution policy from Undefined to RemotelySigned with the beneath command
Fix-ExecutionPolicy -ExecutionPolicy RemoteSigned
Ensure that the policy got updated properly past executing the Get command as function of step-four
Now execute the PowerShell script as ".\<> past navigating on the respective folder location of the script
Once the files are uploaded successfully, please revert the execution policies back to its original state by executing the below line
Set-ExecutionPolicy Undefined -Scope LocalMachine
Output:
Files uploaded to SharePoint Library:
In the output, you can see the uploaded user name.

This is how upload files to sharepoint online using powershell.
Read: How to Change SharePoint Site Logo + PowerShell
At present, permit us see how to upload documents from network drive to SharePoint using PowerShell.
The user wants to drift all the documents from his network drive to the SharePoint document library as part of data migration. Since there are millions of files in the user network bulldoze, I can't inquire the user to upload all his files i by ane nor with the explorer view. Copying files manually will take quite a skillful time of time.
I take written a PowerShell script to upload all the user documents to the certificate library. This script I tin schedule on SharePoint server and it can run on its own without user intervention.
The PowerShell script is equally follows:
function UploadDocuments ($WebURL,$DocLibName,$FilePath) { attempt { # Get a variable that points to the folder $Spider web = Get-SPWeb $WebURL $List = $Spider web.GetFolder($DocLibName) $Files = $Listing.Files # Get but the name of the file from the whole path $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1) # Load the file into a variable $File= Get-ChildItem $FilePath # Upload it to SharePoint $Files.Add together($DocLibName +"/" + $FileName,$File.OpenRead(),$truthful) $web.Dispose() } take hold of { write-host "Error: $($_.Exception.Message)" -foregroundcolor red -BackgroundColor Yellowish } } # Gear up the variables $WebURL = "<< Site URL >>" $DocLibName = "Docs" $fileDirectory = "C:\Temp\PS Testing\T\*.*" foreach($fileName in Become-ChildItem $fileDirectory) { #Reading file by file UploadDocuments -WebURL $WebURL -DocLibName $DocLibName -FilePath $fileName.FullName Write-Host "Uploaded File=" $fileName.Name } write-host "Script executed successfully !!!" -foregroundcolor White -BackgroundColor Dark-green
How to execute this script:
Please follow the beneath steps to execute the PowerShell script:
- Log on to Application Server (where you tin can see Central admin)
- Open SharePoint 2013 management shell every bit administrator
- Copy/Save above script equally "UploadDocuments_onSharePointServer.ps1" (Y'all can change the name if you want there is no dependency of the file name) in c:\
- Navigate on to c:\ in the Direction shell
- Execute the script by typing ".\<<FileName>>"

- This volition upload all the file in "C:\Temp\PS Testing\T" folder
Files in folder "C:\Temp\PS Testing\T"

Output in Management Vanquish:

Files uploaded to SharePoint Library:

Allow u.s.a. see, how to upload documents from local drive to SharePoint 2016/2013 document library using PowerShell.
I am sure almost of us might have experienced this upshot "tin't upload large files to SharePoint". Past default, the maximum size for uploading files is gear up to 250 MB. The maximum file size that information technology can go upward to is 2,047 megabytes. If the file size is greater than 2 GB you will see one of the beneath errors:
- An unexpected error has occurred
- The page cannot be displayed
- An unknown error occurred
- HTTP 404 – Page Not Found
- Asking timed Out
In fact sometimes the user might see one these fault even if the file size is only 500 MB. This can occur due to various reasons now I would like to talk over a few cases with the solutions for each.
Notation: File size parameter/holding is at the spider web application level, every bit per Microsoft best practices information technology is strongly recommended non to increase the size because it will touch on the performance of that web application.
Case-I: Maximum upload size for spider web application is less than the file size:
As discussed just before the default file size of a spider web awarding is 250 MB. Increase the file size for the required web application by post-obit the beneath steps.
Log on to awarding server with the FARM administrator account.
Click on Manage spider web application under Web applications in SharePoint Central Admin.
Key Administration -> Application Direction -> Manage spider web application.

It volition list all the Web Applications in the FARM
Select the spider web application in which you want to increase the file size and click on General setting from ribbon control.

Information technology will bear witness all the General Settings of the spider web Application like Default Quota Template, Alerts, RSS settings, Recycle Bin settings of web application and Maximum upload size limit
You should be able to see as below past default.

Now modify it to 2047 MB to support files up to 2GB and click ok
Instance II: Increment the connexion fourth dimension-out settings in IIS:
While uploading large files, there are chances that the request will timeout. By default, the IIS connection time-out setting is 120 seconds. Follow these steps to increase the connectedness time-out setting,
Click Outset, signal to All Programs, point to Administrative Tools, and and then click Internet Data Services (IIS) Manager.
Right-click the virtual server that y'all want to configure, and then click Backdrop.
Click the Web Site tab. Under Connections, type the number of seconds that you want in the Connectedness time-out box, and then click OK.


Case III: Increase the default chunk size for large files:
The large-file-chunk-size holding sets the amount of information that can be read from server running SQL Server at one time.
If you take a file that is greater than your chunk size (such equally 70 MB when the chunk size is fix to 5 MB), the file would be read in 14 chunks (70 / five).
The clamper size is not related to the maximum upload file size.
The chunk size only specifies the corporeality of data that tin can be read from a file at one time. Past default, the large-file-chunk-size belongings is set to 5 MB.
Check if the 'big-file-chunk-size' property is ready or not
Stsadm -o getproperty -propertyname big-file-chunk-size
In order to ready the large–file–clamper–size property, we need to use the command line. This holding is configured for a server or server farm, and cannot be configured for an individual web app server. To set up this property, use the following syntax:
Stsadm.exe –o setproperty –pn large–file–chunk–size –pv
More on this command is bachelor at Large-file-chunk-size: Stsadm property (Office SharePoint Server)
After making a change to this holding, perform an iisreset/noforce.
This is how, we tin set up a few errors while uploading large files to SharePoint like, unable to upload big file to sharepoint, can not upload large file to sharepoint, an unexpected fault has occurred in sharepoint 2013, the page cannot be displayed in sharepoint 2013, the webpage cannot be found http 404 sharepoint 2013, asking timed out sharepoint 2013, etc.
Let us encounter, how to migrate files with the folder structure to the SharePoint 2013 certificate library using PowerShell. As function of a migration project, we get a request from an end-user to drift their data from various places.
Here, I would like to accept one of the scenarios to upload files from the local drive/network share with the aforementioned folder structure into SharePoint.
Local Binder structure:

PowerShell Script to drift document with folder structure in SharePoint 2013
Below is the PowerShell script to drift document with binder construction in SharePoint 2013.
try { #Referencing to SharePoint PowerShell Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue Start-SPAssignment -Global #Recursive Function to read through all the files and folders till the leafage node function Recurse([string]$path, $spider web, $docLibrary,$bulldoze) { $objFStream = new-object -com scripting.filesystemobject #Fetching the current folder proper name in the network drive path $binder = $objFStream.getfolder($path) $fldPath = $path.Supplant($drive, ").Replace('\', '/') #I am removing the current folder name to create destination folder path to upload the files. $desPath = ($fldPath + '$$').Replace($folder.Proper noun + '$$', ") Write-Host "Exporting data from folder :: "$folder.Name #Validating for the existence of the folder, if the folder is non existed in Library I am creating the binder in document library $objFldVald = $web.GetFolder($docLibrary.RootFolder.ServerRelativeUrl + $fldPath); if ($objFldVald.Exists -eq $simulated) { $docFldCreate = $docLibrary.Items.Add($docLibrary.RootFolder.ServerRelativeUrl.TrimEnd() + $desPath.TrimEnd('/'), [Microsoft.SharePoint.SPFileSystemObjectType]"Binder", $folder.Proper name); $docFldCreate.Update() } #Reading all the files in the current folder foreach ($objFile in $folder.files) { #Create file stream object from file $fileStream = ([System.IO.FileInfo] (Get-Item $objFile.Path)).OpenRead() $contents = new-object byte[] $fileStream.Length $fileStreamLength = $fileStream.Read($contents, 0, [int]$fileStream.Length); $fileStream.Shut(); #Add file to document library in the same folder as in Network drive. $DocLibFld = $web.getfolder($docLibrary.RootFolder.ServerRelativeUrl.TrimEnd() + $fldPath) [Microsoft.SharePoint.SPFile]$spFile = $DocLibFld.Files.Add together($DocLibFld.Url + "/" + $objFile.Name, $contents, $true) Write-Host "File =" $objFile.Name "`tUploaded to " $spider web.Url"/"$DocLibFld } #Checking if there whatever sub folders in the current folder if in that location any I am calling the Rucrse loop to procedure the folder. foreach ($objSubFld in $binder.subfolders) { Recurse $objSubFld.path $spider web $docLibrary $drive } } #Enter the site URL. $webUrl = "http://sharepoint13:12345/" $web = Get-SPWeb -Identity $webUrl #Mention the document library name in which the files demand to be uploaded. $docLibrary = $web.Lists["Documents"] #Provide the path of the local binder to be migrated to SharePoint. Recurse "S:\Export Data" $web $docLibrary 'South:' Write-Host "Migration Completed Sucessfully …!!!" $spider web.Close() End-SPAssignment -Global } take hold of { Write-Host "`n Error:: $($_.Exception.Message)" -ForegroundColor Scarlet -BackgroundColor Yellow }
The power of this script is:
– It can upload any type of files and I accept tested with
- Word Documents
- Excel Files
- PPT documents
- Microsoft Project Planner documents
- Paradigm files
- Text files
- No limit on the depth of the folder
- No limit on the number of files in a binder to be uploaded
- NO HARD CODING OF Whatever LIMITS / DOCUMENT TYPES
The output for the to a higher place script:

This is how to migrate files in SharePoint 2013 with folder construction using PowerShell.
Yous may like post-obit PowerShell SharePoint tutorials:
- Display warning bulletin in SharePoint site using PowerShell
- How to activate SharePoint Publishing Characteristic Programmatically using CSOM and PowerShell
- How to remove SharePoint Online Modernistic Page Title using PowerShell
- The file is not digitally signed PowerShell script
- Enable or Disable List Throttling using PowerShell in SharePoint
In this SharePoint tutorial, we learned, how to upload files to SharePoint using PowerShell? And how to upload large files to sharepoint 2013/2016/2019.
I am Krishna.Vandanapu a SharePoint architect working in It from terminal 13+ years, I worked in SharePoint 2007, 2010, 2013, 2016 and Office 365. I have extensive hands on experience in customizing SharePoint sites from end to end. Expertise in SharePoint migration tools like Sharegate, Doc Ave and Metalogix. Migrated SharePoint sites from SharePoint 2007 to 2010 and 2010 to 2013 several times seamlessly. Implementing CSOM with Microsoft best practices. Spent quality time in configuring SharePoint application services like User Profile, Search, Managed Meta information services etc. At present exploring SharePoint Framework and SharePoint 2019
Source: https://www.enjoysharepoint.com/upload-files-to-sharepoint-using-powershell/
0 Response to "Powershell Script to Upload Files to Dropbox"
Post a Comment