Upload documents to SharePoint document library using PowerShell Remotely

powershell upload file to sharepoint online document library remotely
SharePoint deveopment training course

This PowerShell SharePoint tutorial explains, how to upload documents to SharePoint document library using PowerShell remotely. We will also see, how to upload document to SharePoint Online document library using PowerShell.

Today in this article I would like to advance the script to upload the documents from user’s machine also called remote data upload. Since we can’t get the object of 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 last time that user wants to migrate 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 drive, I can’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 time.

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

Upload documents to SharePoint document library 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)
{
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.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 = "<<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 us walk through the script:

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

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

The below line is to associate the user 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 System.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 above line destination is the name of the document library

  • $File.Name is the 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 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 save the PS1 script
  • Execute the script by typing “.\UploadDocuments_With Credentials.ps1” as shown in the below screenshot.
Upload documents to SharePoint document library using PowerShell Remotely
  • 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.

Upload documents to SharePoint document library using PowerShell Remotely

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

Upload documents to SharePoint Document Library using PowerShell Remotely with default account

Here 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’s 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 but it will upload the document with “SYSTEM ACCOUNT” as user name.

The requirement still remains the same as last time that user wants to migrate 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 drive, I can’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 time.

The below PowerShell script uploads all the user documents to document library. This script I can run request end-user to execute on his local machine as and when he/she require. Another way is that I can 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 name with the destination document library path
$objFile = $destination+$File.Name
#This will upload the file in document library with "System Account" as user name
Invoke-WebRequest -Uri $objFile -Body $content -Method PUT -UseDefaultCredentials
}
catch {
Write-Host "Error:: $($_.Exception.Message)" -foregroundcolor red -BackgroundColor Yellow
}
}
# Set 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
#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. 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:

Please follow the below steps to execute the PowerShell script:

  • Save the above script as “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” as shown in the below screenshot.
Upload documents to SharePoint Document Library using PowerShell Remotely with default account
  • 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.

Upload documents to SharePoint Document Library using PowerShell

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

Upload documents to document library using PowerShell Remotely in SharePoint Online

This SharePoint Online tutorial explains, how to upload documents to document library using PowerShell Remotely in SharePoint Online Office 365.

I would like 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 as last time 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 one 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 document library. This script I can run request end-user to execute on his local machine as and when he/she require. Another way is that I can run on behalf of the business user on my machine 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 = "krishna@OnlySharePoint2013.onmicrosoft.com"
$SiteURL = https://onlysharepoint2013.sharepoint.com/sites/krishna
#Specify Local folder name where the files are to be uploaded
$Folder = "G:\KVN Articles\PS Testing\Files"
$DocLibName = "Finance"

$startedTime = Get-Date
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.Client.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\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.Client.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.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
#Uploading file to document library
$Upload = $List.RootFolder.Files.Add($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 !!!"
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}

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

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

Steps to be followed to ensure the smooth 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 PowerShell command-let with Run as Administrator

Check the “execution policies” for PowerShell in user machine by executing below command in PowerShell command let

Get-ExecutionPolicy -List

The above command will get all the existing policies of the user mostly the output will be as follows:

ScopeExecutionPolicy
MachinePolicyUndefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine  Undefined

We need to change the execution policy from Undefined to RemotelySigned with the below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Ensure that the policy got updated properly by executing the Get command as part of step-4

Now execute the PowerShell script as “.\<> by 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.

upload documents to sharepoint online document library using powershell

You may like following PowerShell SharePoint tutorials:

This SharePoint tutorial, we learned how to upload documents to SharePoint document library remotely using PowerShell.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Krishna Vandanapu

I am Krishna.Vandanapu a SharePoint architect working in IT from last 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 data services etc. Now exploring SharePoint Framework and SharePoint 2019

View all posts by Krishna Vandanapu →