Powershell Upload File to Sharepoint Online Document Library

Microsoft Teams

In this PowerShell SharePoint tutorial, we will discuss how to upload files to SharePoint using PowerShell.

Today in this article I would like to advance the script to upload the documents from user's car besides called remote data upload. Since we can't get 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 as 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 at that place are millions of files in the user network drive, I can't ask the user to upload all his files one by ane nor with the explorer view. Copying files manually will take quite a skilful time of time.

The below PowerShell script uploads all the user documents to document library. This script I tin can run request end-user to execute on his local machine every bit and when he/she require. Another way is that I can run on behalf of the business organisation user on my machine without doing a remote to the SharePoint server.

Upload files to sharepoint using PowerShell Remotely

Let the states come across, 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 part UploadDocuments($destination, $File,$userID, $securePasssword) { try { # Since we're doing this remotely, we need to authenticate $credentials = New-Object System.Management.Automation.PSCredential ($userID, $securePasssword)  # Upload the file $webclient = New-Object System.Internet.WebClient $webclient.Credentials = $credentials $webclient.UploadFile($destination + "/" + $File.Proper noun, "PUT", $File.FullName) } catch { Write-Host "Error:: $($_.Exception.Message)" -foregroundcolor scarlet -BackgroundColor Yellow }  } # Set 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.Proper noun } Write-Host "Script executed Successfully"        

Note:
Whoever is running script should have contribute access to the SharePoint document library.

Permit u.s.a. walk through the script:

I am reading password with the below line of lawmaking in PowerShell command prompt:

          $securePasssword = Read-Host "Please enter the countersign:" -AsSecureString        

The below line is to acquaintance the user name and password which volition exist used while creating object to the SharePoint site.

          $credentials = New-Object Organisation.Direction.Automation.PSCredential ("<<Domain\userID>", $securePasssword)        

Nosotros are making telephone 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 document library:

          $webclient.UploadFile($destination + "/" + $File.Proper noun, "PUT", $File.FullName)        

In the in a higher place line destination is the name of the certificate library

  • $File.Name is the proper name of the file to be created as in document library
  • $File.FullName is the path of the file from where it needs to be uploaded from

How to run this PowerShell script?

Please follow the beneath steps to execute the PowerShell script:

  • Save the above script as "UploadDocuments_With Credentials.ps1"
  • Open up PowerShell Command let as administrator
  • Navigate to the folder where you salve the PS1 script
  • Execute the script by typing ".\UploadDocuments_With Credentials.ps1" as shown in the beneath screenshot.
Upload documents to SharePoint document library using PowerShell Remotely
upload files to sharepoint using powershell
  • This script has will upload all the file in "C:\Temp\PS Testing\T" folder every bit mentioned in the code.

Output:
Files uploaded to SharePoint Library:
In the output you tin can see the uploaded user proper name.

Upload documents to SharePoint document library using PowerShell Remotely
How to upload files to sharepoint using powershell

Note: This script will non work for SharePoint online sites.

Read: PowerShell SharePoint list operations and PowerShell SharePoint site collection example.

How to upload files to SharePoint using PowerShell Remotely with default account

Here we volition encounter how to upload documents to SharePoint Document Library using PowerShell Remotely with the default business relationship.

Now, I would like to advance the script to upload the documents from user'southward automobile as well chosen 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 but information technology will upload the certificate with "SYSTEM Account" as user name.

The requirement still remains the same as last time that the user wants to drift all the documents from his network drive to the SharePoint certificate library as role 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 by 1 nor with the explorer view. Copying files manually will take quite a practiced time of time.

The beneath PowerShell script uploads all the user documents to the document library. This script I can run asking finish-user to execute on his local machine as and when he/she crave. Some other way is that I can run on behalf of the business organisation user on my automobile without doing a remote to the SharePoint server.

The PowerShell script is every bit follows:

          # This script is to upload the documents from local binder to Sharepoint Document library without user stamp  function UploadDocuments($destination, $File) { try { #Rading file data with IO stream $content = [Organization.IO.File]::ReadAllBytes($File) #appending file name with the destination document library path $objFile = $destination+$File.Name #This volition upload the file in document library with "System Business relationship" as user proper noun Invoke-WebRequest -Uri $objFile -Trunk $content -Method PUT -UseDefaultCredentials } take hold of { Write-Host "Error:: $($_.Exception.Message)" -foregroundcolor red -BackgroundColor Yellowish } } # Set the variables $destination = "<< Site URL >>" $fileDirectory = "C:\Krishna\PowerShell Scripts\PS Testing\*.*" #Reading through the document library foreach($fileName in Become-ChildItem $fileDirectory) { #Calling method to upload the files from local folder UploadDocuments -destination $destination -File $fileName #Printing file name in Powershell command prompt Write-Output "Uploaded File" $fileName } Write-Host "Script executed Successfully" #Note: This script upload the files with System account. Notwithstanding who ever is executing the script must have # contribute access on document library.        

Note:
Whoever is running script should have contributed admission to the document library.

Since I have added comments for each and every line the code is cocky-explanatory.

How to execute this PowerShell script:

Please follow the below steps to execute the PowerShell script:

  • Relieve the above script as "UploadDocuments_With out Credentials.ps1"
  • Open PowerShell Command let equally ambassador
  • Navigate to the folder where you lot save the PS1 script
  • Execute the script by typing ".\UploadDocuments_With out Credentials.ps1" as shown in the beneath screenshot.
upload files to SharePoint using PowerShell
upload file to sharepoint online programmatically
  • This script has will upload all the file in "C:\Temp\PS Testing\T" folder equally mentioned in the lawmaking.

Output:
Files uploaded to SharePoint Library:
In the output you can come across the uploaded user name.

upload files to sharepoint online using powershell
upload file to sharepoint online programmatically

Note: This script will not work for SharePoint online sites.

Read: 40 Useful PowerShell SharePoint Commands.

Upload files to SharePoint online using PowerShell

Permit us 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.

Yet, the requirement still remains the aforementioned as last fourth dimension that user wants to migrate all the documents from his network / local drive to SharePoint online document library as part data migration.

Since there are millions of files in the user's drive, I can't ask the user to upload all his files one by ane nor with the explorer view. Copying files manually will take quite a good time of time.

The below PowerShell script uploads all the user documents to SharePoint Online certificate library. This script I tin run request end-user to execute on his local automobile equally and when he/she require. Another style is that I tin can run on behalf of the business concern user on my automobile seamlessly.

Below is the PowerShell script to upload documents to the SharePoint Online document library remotely.

          try { #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 be uploaded $Folder = "G:\KVN Articles\PS Testing\Files" $DocLibName = "Finance"  $startedTime = Go-Engagement Write-Host "Time Started = " $startedTime  #Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM Add-Type -Path "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Customer.dll" Add-Blazon -Path "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.SharePoint.Customer.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Customer.Runtime.dll" #Reading Countersign from PowerShell Command line $Countersign = 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 $List = $Context.Spider web.Lists.GetByTitle($DocLibName) $Context.Load($List) $Context.ExecuteQuery() #Reading through the local binder for files Foreach ($File in (dir $Folder -File)) { #Reading File data using IO stream object $FileStream = New-Object IO.FileStream($File.FullName,[Organization.IO.FileMode]::Open) $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation $FileCreationInfo.Overwrite = $true $FileCreationInfo.ContentStream = $FileStream $FileCreationInfo.URL = $File #Uploading file to document library $Upload = $Listing.RootFolder.Files.Add($FileCreationInfo) $Context.Load($Upload) $Context.ExecuteQuery() Write-Host "Uploaded File=" $File.Proper noun } $completedTime = Go-Engagement Write-Host "Time Completed = " $completedTime Write-Host "Script Excecuted Successfully !!!" } catch { write-host "Fault: $($_.Exception.Message)" -foregroundcolor red }        

I strongly believe that the script is self-explanatory as I have added comments for most of the lines.

Notation:
To execute this script user must install the SharePoint client components SDK on his/her machine.

Steps to exist followed to ensure the smoothen execution:

Ensure that SharePoint Client components SDK installed on the user car

Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Customer.Runtime.dll paths mentioned in the script are the same as the user's car

Open PowerShell control-let with Run every bit Ambassador

Cheque the "execution policies" for PowerShell in user machine by executing below command in PowerShell control let

          Become-ExecutionPolicy -Listing        

The above control will go all the existing policies of the user generally the output volition be every bit 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 below control

          Set up-ExecutionPolicy -ExecutionPolicy RemoteSigned        

Ensure that the policy got updated properly past executing the Get command as part of step-iv

At present execute the PowerShell script every bit ".\<> by navigating on the corresponding folder location of the script

Once the files are uploaded successfully, please revert the execution policies back to its original state past executing the below line

          Set-ExecutionPolicy Undefined -Telescopic LocalMachine        

Output:
Files uploaded to SharePoint Library:
In the output, yous can see the uploaded user name.

upload file to sharepoint library using powershell
upload file to sharepoint library using powershell

This is how upload files to sharepoint online using powershell.

Read: How to Change SharePoint Site Logo + PowerShell

Upload files from network drive to SharePoint using PowerShell

Now, let us run into how to upload documents from network drive to SharePoint using PowerShell.

The user wants to migrate all the documents from his network drive to the SharePoint document library every bit role 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 by i nor with the explorer view. Copying files manually will take quite a good time of fourth dimension.

I accept written a PowerShell script to upload all the user documents to the document library. This script I can schedule on SharePoint server and it tin can run on its own without user intervention.

The PowerShell script is as follows:

          function UploadDocuments ($WebURL,$DocLibName,$FilePath) { endeavor {  # Get a variable that points to the binder $Spider web = Get-SPWeb $WebURL $List = $Web.GetFolder($DocLibName) $Files = $List.Files  # Get simply the proper noun of the file from the whole path $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+one)  # Load the file into a variable $File= Get-ChildItem $FilePath  # Upload it to SharePoint $Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$true) $spider web.Dispose() } catch { write-host "Error: $($_.Exception.Message)" -foregroundcolor carmine -BackgroundColor Xanthous } } # Gear up the variables $WebURL = "<< Site URL >>" $DocLibName = "Docs" $fileDirectory = "C:\Temp\PS Testing\T\*.*" foreach($fileName in Get-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 below steps to execute the PowerShell script:

  • Log on to Awarding Server (where you tin can see Key admin)
  • Open SharePoint 2013 management trounce every bit administrator
  • Re-create/Save above script as "UploadDocuments_onSharePointServer.ps1" (You tin can alter the proper noun if you want at that place is no dependency of the file proper name) in c:\
  • Navigate on to c:\ in the Management shell
  • Execute the script by typing ".\<<FileName>>"
sharepoint upload file to document library powershell
sharepoint upload file to document library powershell
  • This will upload all the file in "C:\Temp\PS Testing\T" folder

Files in folder "C:\Temp\PS Testing\T"

upload documents from network drive to SharePoint using powershell

Output in Management Shell:

upload file to sharepoint document library using powershell
How to upload files to SharePoint using PowerShell

Files uploaded to SharePoint Library:

upload file to sharepoint document library powershell
upload files to sharepoint using powershell

Let u.s.a. see, how to upload documents from local bulldoze to SharePoint 2016/2013 document library using PowerShell.

Unable to upload large files to SharePoint using PowerShell

I am sure most of united states might have experienced this issue "can't upload large files to SharePoint". Past default, the maximum size for uploading files is set to 250 MB. The maximum file size that information technology tin go upwards to is 2,047 megabytes. If the file size is greater than 2 GB y'all will run into one of the below errors:

  • An unexpected mistake has occurred
  • The page cannot be displayed
  • An unknown mistake occurred
  • HTTP 404 – Page Not Found
  • Request timed Out

In fact sometimes the user might see one these error even if the file size is only 500 MB. This tin can occur due to various reasons now I would like to discuss a few cases with the solutions for each.

Note: File size parameter/property is at the web application level, as per Microsoft best practices it is strongly recommended not to increment the size because information technology will impact the performance of that web application.

Case-I: Maximum upload size for web awarding is less than the file size:

Every bit discussed just earlier the default file size of a web application is 250 MB. Increase the file size for the required web application by following the below steps.

Log on to application server with the Subcontract administrator account.

Click on Manage web application under Web applications in SharePoint Central Admin.

Primal Assistants -> Application Management -> Manage web awarding.

Request timed Out sharepoint
tin non upload large file to sharepoint

It volition list all the Web Applications in the Subcontract

Select the web application in which you want to increase the file size and click on General setting from ribbon command.

unable to upload large file to sharepoint 2013
unable to upload large file to sharepoint 2013

It volition show all the Full general Settings of the web Application similar Default Quota Template, Alerts, RSS settings, Recycle Bin settings of web application and Maximum upload size limit

Yous should be able to see equally below by default.

unable to upload large file to sharepoint
unable to upload large file to sharepoint

Now alter information technology to 2047 MB to back up files up to 2GB and click ok

Case II: Increase the connection time-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 connection time-out setting,

Click Start, betoken to All Programs, point to Administrative Tools, then click Net Data Services (IIS) Director.

Right-click the virtual server that you want to configure, and so click Properties.

Click the Web Site tab. Under Connections, blazon the number of seconds that y'all want in the Connection fourth dimension-out box, and then click OK.

upload large file to sharepoint 2016
upload big file to sharepoint 2016
upload large file to sharepoint 2013
upload large file to sharepoint 2013

Example III: Increment the default chunk size for large files:

The large-file-clamper-size property sets the amount of information that can exist read from server running SQL Server at one fourth dimension.

If y'all have a file that is greater than your clamper size (such equally lxx MB when the clamper size is set to 5 MB), the file would be read in 14 chunks (70 / 5).

The chunk size is non related to the maximum upload file size.

The clamper size but specifies the amount of data that can exist read from a file at one time. By default, the large-file-chunk-size property is set to five MB.

Check if the 'large-file-chunk-size' property is gear up or not

          Stsadm -o getproperty -propertyname large-file-clamper-size        

In order to set the large–file–clamper–size property, nosotros need to apply the command line. This property is configured for a server or server farm, and cannot exist configured for an private web app server. To set this holding, utilize the following syntax:

          Stsadm.exe –o setproperty –pn big–file–chunk–size –pv        

More on this command is available at Large-file-clamper-size: Stsadm property (Office SharePoint Server)

After making a change to this property, perform an iisreset/noforce.

This is how, nosotros can gear up a few errors while uploading large files to SharePoint like, unable to upload big file to sharepoint, tin not upload large file to sharepoint, an unexpected error 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.

Migrate SharePoint certificate library with binder structure

Let us see, how to drift files with the binder structure to the SharePoint 2013 document library using PowerShell. Every bit part of a migration project, nosotros get a request from an end-user to migrate their information from diverse places.

Here, I would like to take one of the scenarios to upload files from the local drive/network share with the aforementioned binder structure into SharePoint.

Local Folder structure:

migrate sharepoint document library
drift sharepoint document library

PowerShell Script to migrate document with folder construction in SharePoint 2013

Below is the PowerShell script to drift document with folder construction in SharePoint 2013.

          endeavour { #Referencing to SharePoint PowerShell Add together-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue Start-SPAssignment -Global #Recursive Function to read through all the files and folders till the leaf node function Recurse([string]$path, $spider web, $docLibrary,$drive) { $objFStream = new-object -com scripting.filesystemobject #Fetching the current folder proper noun in the network bulldoze path $folder = $objFStream.getfolder($path) $fldPath = $path.Replace($drive, ").Replace('\', '/') #I am removing the current folder proper noun to create destination folder path to upload the files. $desPath = ($fldPath + '$$').Supercede($folder.Name + '$$', ") Write-Host "Exporting data from folder :: "$folder.Name #Validating for the being of the folder, if the folder is not existed in Library I am creating the folder in certificate library $objFldVald = $web.GetFolder($docLibrary.RootFolder.ServerRelativeUrl + $fldPath); if ($objFldVald.Exists -eq $false) { $docFldCreate = $docLibrary.Items.Add together($docLibrary.RootFolder.ServerRelativeUrl.TrimEnd() + $desPath.TrimEnd('/'), [Microsoft.SharePoint.SPFileSystemObjectType]"Folder", $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.Close(); #Add file to certificate library in the same folder every bit in Network drive. $DocLibFld = $spider web.getfolder($docLibrary.RootFolder.ServerRelativeUrl.TrimEnd() + $fldPath) [Microsoft.SharePoint.SPFile]$spFile = $DocLibFld.Files.Add($DocLibFld.Url + "/" + $objFile.Name, $contents, $true) Write-Host "File =" $objFile.Name "`tUploaded to " $web.Url"/"$DocLibFld } #Checking if there whatsoever sub folders in the current binder if in that location any I am calling the Rucrse loop to procedure the folder. foreach ($objSubFld in $folder.subfolders) { Recurse $objSubFld.path $spider web $docLibrary $bulldoze } } #Enter the site URL. $webUrl = "http://sharepoint13:12345/" $spider 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 exist migrated to SharePoint. Recurse "S:\Export Information" $spider web $docLibrary 'Southward:' Write-Host "Migration Completed Sucessfully …!!!" $web.Shut() Stop-SPAssignment -Global } grab { Write-Host "`n Error:: $($_.Exception.Message)" -ForegroundColor Red -BackgroundColor Yellowish }                  

The power of this script is:
– It can upload whatever type of files and I take tested with

  • Give-and-take Documents
  • Excel Files
  • PDF
  • PPT documents
  • Microsoft Project Planner documents
  • Prototype files
  • Text files
  • No limit on the depth of the folder
  • No limit on the number of files in a folder to exist uploaded
  • NO Hard CODING OF ANY LIMITS / DOCUMENT TYPES

The output for the above script:

PowerShell to Migrate files & folder structure in SharePoint tutorial
PowerShell to Migrate files & folder structure in SharePoint tutorial

This is how to migrate files in SharePoint 2013 with folder structure using PowerShell.

You may like post-obit PowerShell SharePoint tutorials:

  • Display alert message in SharePoint site using PowerShell
  • How to activate SharePoint Publishing Feature Programmatically using CSOM and PowerShell
  • How to remove SharePoint Online Modern Page Championship using PowerShell
  • The file is not digitally signed PowerShell script
  • Enable or Disable List Throttling using PowerShell in SharePoint

In this SharePoint tutorial, nosotros learned, how to upload files to SharePoint using PowerShell? And how to upload large files to sharepoint 2013/2016/2019.

tovartheappring.blogspot.com

Source: https://www.enjoysharepoint.com/upload-files-to-sharepoint-using-powershell/

Artikel Terkait

Belum ada Komentar untuk "Powershell Upload File to Sharepoint Online Document Library"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel