Sharepoint Create a Record in a Doc Library Without Uploading a File
In this PowerShell SharePoint tutorial, nosotros will talk over how to upload files to SharePoint using PowerShell.
Today in this article I would similar to advance the script to upload the documents from user's machine likewise chosen 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 ane of the ways to become the object for a site.
The requirement nevertheless remains the same as terminal time that the user wants to migrate 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 tin can't enquire the user to upload all his files one by one nor with the explorer view. Copying files manually will take quite a expert time of fourth dimension.
The beneath PowerShell script uploads all the user documents to document library. This script I tin can run request end-user to execute on his local motorcar every bit and when he/she crave. Some other way is that I can run on behalf of the business user on my machine without doing a remote to the SharePoint server.
Permit u.s. see, 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 document library REMOTELY with user Credentails function UploadDocuments($destination, $File,$userID, $securePasssword) { endeavour { # Since nosotros're doing this remotely, nosotros need to cosign $credentials = New-Object System.Direction.Automation.PSCredential ($userID, $securePasssword) # Upload the file $webclient = New-Object Arrangement.Net.WebClient $webclient.Credentials = $credentials $webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName) } catch { Write-Host "Error:: $($_.Exception.Message)" -foregroundcolor red -BackgroundColor Yellow } } # Set the variables $destination = "<<Certificate 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 name } Write-Host "Script executed Successfully"
Note:
Whoever is running script should have contribute admission to the SharePoint document library.
Permit us walk through the script:
I am reading countersign with the below line of code in PowerShell command prompt:
$securePasssword = Read-Host "Please enter the countersign:" -AsSecureString
The beneath line is to acquaintance the user proper name and password which will be 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 Organization.Net.WebClient $webclient.Credentials = $credentials $webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)
Uploading the file to SharePoint document library:
$webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)
In the to a higher place line destination is the name of the document library
- $File.Proper noun is the proper noun 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:
- Salvage the above script as "UploadDocuments_With Credentials.ps1"
- Open PowerShell Command let as ambassador
- Navigate to the folder where you salve 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" binder every bit mentioned in the code.
Output:
Files uploaded to SharePoint Library:
In the output yous can encounter the uploaded user name.
Note: This script will not work for SharePoint online sites.
Read: PowerShell SharePoint list operations and PowerShell SharePoint site collection example.
Hither we will see how to upload documents to SharePoint Document Library using PowerShell Remotely with the default account.
Now, I would like to advance the script to upload the documents from user'due south machine likewise 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 but information technology will upload the document with "Organisation Account" as user name.
The requirement still remains the same as last fourth dimension that the user wants to migrate all the documents from his network bulldoze to the SharePoint certificate library as office of data migration. Since there are millions of files in the user network drive, I can't enquire 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 fourth dimension.
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 run on behalf of the business 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 function UploadDocuments($destination, $File) { try { #Rading file data with IO stream $content = [System.IO.File]::ReadAllBytes($File) #appending file proper name with the destination document library path $objFile = $destination+$File.Proper noun #This will upload the file in document library with "System Business relationship" equally user proper noun Invoke-WebRequest -Uri $objFile -Trunk $content -Method PUT -UseDefaultCredentials } catch { Write-Host "Error:: $($_.Exception.Bulletin)" -foregroundcolor red -BackgroundColor Yellow } } # Set the variables $destination = "<< Site URL >>" $fileDirectory = "C:\Krishna\PowerShell Scripts\PS Testing\*.*" #Reading through the certificate library foreach($fileName in Get-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 Organization account. However who ever is executing the script must have # contribute access on document library.
Note:
Whoever is running script should have contributed access to the document library.
Since I have added comments for each and every line the code is self-explanatory.
How to execute this PowerShell script:
Delight follow the below steps to execute the PowerShell script:
- Relieve the above script as "UploadDocuments_With out Credentials.ps1"
- Open PowerShell Command permit equally administrator
- Navigate to the binder where you save the PS1 script
- Execute the script by typing ".\UploadDocuments_With out Credentials.ps1" as shown in the below screenshot.
- This script has will upload all the file in "C:\Temp\PS Testing\T" folder every bit mentioned in the lawmaking.
Output:
Files uploaded to SharePoint Library:
In the output yous can come across the uploaded user name.
Annotation: This script will not work for SharePoint online sites.
Read: 40 Useful PowerShell SharePoint Commands.
Let us meet, how to upload files to sharepoint online using powershell.
I would similar to speak about the process to upload the documents to the SharePoint Online site from your local environment.
However, the requirement still remains the same every bit last fourth dimension that user wants to migrate all the documents from his network / local drive to SharePoint online certificate library every bit part data migration.
Since there are millions of files in the user'due south drive, I tin't ask the user to upload all his files one by one nor with the explorer view. Copying files manually will take quite a good time of fourth dimension.
The beneath 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 auto as and when he/she crave. Some other way is that I can run on behalf of the business user on my motorcar 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 = "[electronic mail protected]" $SiteURL = https://onlysharepoint2013.sharepoint.com/sites/krishna #Specify Local folder name where the files are to be uploaded $Folder = "One thousand:\KVN Articles\PS Testing\Files" $DocLibName = "Finance" $startedTime = Become-Appointment Write-Host "Time Started = " $startedTime #Add references to SharePoint customer assemblies and cosign to Part 365 site – required for CSOM Add-Blazon -Path "C:\Windows\Microsoft.Cyberspace\assembly\GAC_MSIL\Microsoft.SharePoint.Customer\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Windows\Microsoft.Internet\associates\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll" #Reading Password from PowerShell Command 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.Customer.SharePointOnlineCredentials($User,$Password) $Context.Credentials = $Creds #Creating Object to Document Library $List = $Context.Web.Lists.GetByTitle($DocLibName) $Context.Load($List) $Context.ExecuteQuery() #Reading through the local folder for files Foreach ($File in (dir $Folder -File)) { #Reading File data using IO stream object $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open) $FileCreationInfo = New-Object Microsoft.SharePoint.Customer.FileCreationInformation $FileCreationInfo.Overwrite = $true $FileCreationInfo.ContentStream = $FileStream $FileCreationInfo.URL = $File #Uploading file to certificate library $Upload = $List.RootFolder.Files.Add($FileCreationInfo) $Context.Load($Upload) $Context.ExecuteQuery() Write-Host "Uploaded File=" $File.Proper noun } $completedTime = Get-Date Write-Host "Time Completed = " $completedTime Write-Host "Script Excecuted Successfully !!!" } take hold of { write-host "Error: $($_.Exception.Message)" -foregroundcolor scarlet }
I strongly believe that the script is self-explanatory as I have added comments for most of the lines.
Annotation:
To execute this script user must install the SharePoint client components SDK on his/her machine.
Steps to be followed to ensure the smoothen execution:
Ensure that SharePoint Client components SDK installed on the user machine
Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll paths mentioned in the script are the same as the user's machine
Open up PowerShell command-permit with Run as Administrator
Cheque the "execution policies" for PowerShell in user machine by executing beneath control in PowerShell command let
Get-ExecutionPolicy -Listing
The in a higher place command will get all the existing policies of the user more often than not the output will be as 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 command
Set up-ExecutionPolicy -ExecutionPolicy RemoteSigned
Ensure that the policy got updated properly by executing the Get command as office of step-iv
Now execute the PowerShell script as ".\<> past navigating on the respective folder location of the script
In one case the files are uploaded successfully, please revert the execution policies back to its original country by executing the below line
Set-ExecutionPolicy Undefined -Telescopic LocalMachine
Output:
Files uploaded to SharePoint Library:
In the output, you lot tin come across the uploaded user proper name.
This is how upload files to sharepoint online using powershell.
Read: How to Change SharePoint Site Logo + PowerShell
Now, allow united states of america 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 certificate library as function of information migration. Since at that place are millions of files in the user network bulldoze, I can't ask the user to upload all his files ane by i nor with the explorer view. Copying files manually will take quite a practiced time of time.
I have written a PowerShell script to upload all the user documents to the document library. This script I can schedule on SharePoint server and information technology can run on its own without user intervention.
The PowerShell script is every bit follows:
function UploadDocuments ($WebURL,$DocLibName,$FilePath) { try { # Become a variable that points to the binder $Web = Get-SPWeb $WebURL $List = $Spider web.GetFolder($DocLibName) $Files = $List.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($DocLibName +"/" + $FileName,$File.OpenRead(),$truthful) $web.Dispose() } catch { write-host "Error: $($_.Exception.Message)" -foregroundcolor red -BackgroundColor Yellow } } # Set the variables $WebURL = "<< Site URL >>" $DocLibName = "Docs" $fileDirectory = "C:\Temp\PS Testing\T\*.*" foreach($fileName in Go-ChildItem $fileDirectory) { #Reading file by file UploadDocuments -WebURL $WebURL -DocLibName $DocLibName -FilePath $fileName.FullName Write-Host "Uploaded File=" $fileName.Proper name } write-host "Script executed successfully !!!" -foregroundcolor White -BackgroundColor Dark-green
How to execute this script:
Delight follow the below steps to execute the PowerShell script:
- Log on to Application Server (where you can meet Central admin)
- Open SharePoint 2013 management shell as administrator
- Copy/Salve above script as "UploadDocuments_onSharePointServer.ps1" (You can alter the name if you want there is no dependency of the file name) in c:\
- Navigate on to c:\ in the Management shell
- Execute the script by typing ".\<<FileName>>"
- This will upload all the file in "C:\Temp\PS Testing\T" folder
Files in folder "C:\Temp\PS Testing\T"
Output in Direction Trounce:
Files uploaded to SharePoint Library:
Let united states of america meet, how to upload documents from local drive to SharePoint 2016/2013 document library using PowerShell.
I am certain near of us might accept experienced this result "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 can go upward to is ii,047 megabytes. If the file size is greater than 2 GB you volition see 1 of the below errors:
- An unexpected error has occurred
- The page cannot be displayed
- An unknown fault occurred
- HTTP 404 – Page Not Found
- Request timed Out
In fact sometimes the user might run across 1 these error even if the file size is only 500 MB. This can occur due to various reasons now I would similar to discuss a few cases with the solutions for each.
Notation: File size parameter/property is at the spider web awarding level, equally per Microsoft all-time practices it is strongly recommended not to increase the size because it volition impact the performance of that web awarding.
Case-I: Maximum upload size for web application is less than the file size:
As discussed but before the default file size of a web application is 250 MB. Increment the file size for the required web application past following the beneath steps.
Log on to awarding server with the Farm administrator business relationship.
Click on Manage web application under Web applications in SharePoint Central Admin.
Central Administration -> Application Management -> Manage spider web application.
Information technology will 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.
It will prove all the General Settings of the web Application like Default Quota Template, Alerts, RSS settings, Recycle Bin settings of spider web application and Maximum upload size limit
Yous should exist able to run across every bit below past default.
Now change information technology to 2047 MB to back up files up to 2GB and click ok
Instance II: Increase the connection fourth dimension-out settings in IIS:
While uploading big files, there are chances that the request will timeout. Past default, the IIS connexion time-out setting is 120 seconds. Follow these steps to increase the connectedness time-out setting,
Click First, point to All Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Director.
Correct-click the virtual server that you want to configure, so click Backdrop.
Click the Spider web Site tab. Under Connections, type the number of seconds that you want in the Connection time-out box, then click OK.
Case 3: Increase the default chunk size for large files:
The large-file-chunk-size property sets the amount of data that tin be read from server running SQL Server at ane fourth dimension.
If you have a file that is greater than your chunk size (such as 70 MB when the chunk size is set to 5 MB), the file would exist read in xiv chunks (70 / 5).
The chunk size is not related to the maximum upload file size.
The chunk size simply specifies the amount of data that can exist read from a file at one fourth dimension. By default, the large-file-chunk-size belongings is fix to 5 MB.
Check if the 'large-file-clamper-size' property is set up or not
Stsadm -o getproperty -propertyname large-file-chunk-size
In order to set the large–file–chunk–size property, nosotros need to use the control line. This property is configured for a server or server subcontract, and cannot exist configured for an individual web app server. To set this holding, employ the post-obit syntax:
Stsadm.exe –o setproperty –pn large–file–chunk–size –pv
More on this command is available at Big-file-chunk-size: Stsadm belongings (Office SharePoint Server)
After making a change to this property, perform an iisreset/noforce.
This is how, we can set up a few errors while uploading large files to SharePoint similar, unable to upload big file to sharepoint, tin not upload big file to sharepoint, an unexpected error has occurred in sharepoint 2013, the page cannot be displayed in sharepoint 2013, the webpage cannot be establish http 404 sharepoint 2013, asking timed out sharepoint 2013, etc.
Permit united states see, how to migrate files with the binder structure to the SharePoint 2013 document library using PowerShell. As office of a migration project, we get a request from an end-user to migrate their information from various places.
Here, I would like to take one of the scenarios to upload files from the local drive/network share with the same folder structure into SharePoint.
Local Folder construction:
PowerShell Script to migrate document with folder construction in SharePoint 2013
Below is the PowerShell script to migrate certificate with folder structure in SharePoint 2013.
try { #Referencing to SharePoint PowerShell Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue Showtime-SPAssignment -Global #Recursive Function to read through all the files and folders till the leaf node office Recurse([cord]$path, $web, $docLibrary,$drive) { $objFStream = new-object -com scripting.filesystemobject #Fetching the current folder name in the network drive path $folder = $objFStream.getfolder($path) $fldPath = $path.Replace($bulldoze, ").Supersede('\', '/') #I am removing the current folder name to create destination binder path to upload the files. $desPath = ($fldPath + '$$').Replace($folder.Name + '$$', ") 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 folder in document 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 binder foreach ($objFile in $binder.files) { #Create file stream object from file $fileStream = ([System.IO.FileInfo] (Go-Item $objFile.Path)).OpenRead() $contents = new-object byte[] $fileStream.Length $fileStreamLength = $fileStream.Read($contents, 0, [int]$fileStream.Length); $fileStream.Shut(); #Add file to certificate 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.Proper name, $contents, $true) Write-Host "File =" $objFile.Proper noun "`tUploaded to " $web.Url"/"$DocLibFld } #Checking if at that place whatever sub folders in the current folder if at that place any I am calling the Rucrse loop to process the folder. foreach ($objSubFld in $binder.subfolders) { Recurse $objSubFld.path $spider web $docLibrary $drive } } #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 folder to be migrated to SharePoint. Recurse "Due south:\Export Data" $web $docLibrary 'S:' Write-Host "Migration Completed Sucessfully …!!!" $web.Close() Terminate-SPAssignment -Global } catch { Write-Host "`n Error:: $($_.Exception.Message)" -ForegroundColor Red -BackgroundColor Yellow }
The power of this script is:
– It can upload any type of files and I have tested with
- Discussion Documents
- Excel Files
- PPT documents
- Microsoft Project Planner documents
- Image files
- Text files
- No limit on the depth of the binder
- No limit on the number of files in a folder to be uploaded
- NO Hard CODING OF Whatsoever LIMITS / DOCUMENT TYPES
The output for the to a higher place script:
This is how to migrate files in SharePoint 2013 with binder structure using PowerShell.
You may like following PowerShell SharePoint tutorials:
- Display alert bulletin in SharePoint site using PowerShell
- How to activate SharePoint Publishing Characteristic Programmatically using CSOM and PowerShell
- How to remove SharePoint Online Modern Page Championship using PowerShell
- The file is non 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.
I am Krishna.Vandanapu a SharePoint architect working in IT from last 13+ years, I worked in SharePoint 2007, 2010, 2013, 2016 and Role 365. I have extensive easily on feel in customizing SharePoint sites from cease 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 awarding services similar User Profile, Search, Managed Meta data services etc. Now exploring SharePoint Framework and SharePoint 2019
Source: https://www.enjoysharepoint.com/upload-files-to-sharepoint-using-powershell/
0 Response to "Sharepoint Create a Record in a Doc Library Without Uploading a File"
Post a Comment