Upload files to SharePoint document library using PowerShell - Demo

In 2 steps instantly upload files to SharePoint document library using PowerShell CSOM

2 comments

 82,915 total views,  5 views today

Upload files to SharePoint document library using PowerShell (SharePoint Online) – here in this post – I will show how we can upload multiple files or documents to SharePoint online document library using PowerShell CSOM programmatically from the given directory.

Upload files to SharePoint document library using PowerShell CSOM

Below is the list of files – located in my local directory which I am going to upload to the SharePoint Online document library using PowerShell coding.

Upload files to SharePoint document library using PowerShell CSOM

Making sure no files are available in my SharePoint online “TestDocumentLibrary” before executing the code.

Upload files to SharePoint document library using PowerShell script - Demo

PowerShell script to upload files to SharePoint: upload files to SharePoint document library using PowerShell

Using the below PowerShell script, we can upload files to the SharePoint document library:

#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"
cls



$fileName = "File_Uploading_Report"
#'yyyyMMddhhmm   yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename =  $enddate + '_VMReport.doc'  
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path  

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   


#$logPath = $directoryPath + "\" + $logFileName 

$logPath = $directoryPathForLog + "\" + $logFileName 
  
$isLogFileCreated = $False 



#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#DLL location

$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime


#Files to upload location

$directoryPathForFileToUploadLocation=$directoryPath+"\"+"Files To Upload"
if(!(Test-Path -path $directoryPathForFileToUploadLocation))  
        {  
            New-Item -ItemType directory -Path $directoryPathForFileToUploadLocation
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#Files to upload location ends here.

  

function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
} 



#The below function will upload the file from local directory to SharePoint Online library.

Function FileUploadToSPOnlineLibrary()
{
    param
    (
        [Parameter(Mandatory=$true)] [string] $SPOSiteURL,
        [Parameter(Mandatory=$true)] [string] $SourceFilePath,
        [Parameter(Mandatory=$true)] [string] $File,
        [Parameter(Mandatory=$true)] [string] $TargetLibrary,
        [Parameter(Mandatory=$true)] [string] $UserName,
        [Parameter(Mandatory=$true)] [string] $Password
    )
 
    Try 
    {
       
        $securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force  
        #Setup the Context
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)

        $list = $ctx.Web.Lists.GetByTitle($TargetLibrary)
        $ctx.Load($list)
        $ctx.ExecuteQuery()     
       
        $tarGetFilePath=$siteURL+"/"+"$TargetLibrary"+"/"+$File

        $fileOpenStream = New-Object IO.FileStream($SourceFilePath, [System.IO.FileMode]::Open)  
        $fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation  
        $fileCreationInfo.Overwrite = $true  
        $fileCreationInfo.ContentStream = $fileOpenStream  
        $fileCreationInfo.URL = $File  
        $uploadFileInfo = $list.RootFolder.Files.Add($FileCreationInfo)  
        $ctx.Load($uploadFileInfo)  
        $ctx.ExecuteQuery() 

         
        Write-host -f Green "File '$SourceFilePath' has been uploaded to '$tarGetFilePath' successfully!"
    }
    Catch 
    {
            
            $ErrorMessage = $_.Exception.Message +"in uploading File!: " +$tarGetFilePath
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 


    }
}

#Variables
$siteURL="https://globalsharepoint.sharepoint.com/sites/TestSite/"
$listName="TestDocumentLibrary"
$fromDate="2019-10-28"
$toDate="2019-11-09"
$filesFolderLoaction=$directoryPathForFileToUploadLocation;
$userName = "YourSPOAccount@YourTenantDomain.com"
$password = "YourPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force

#Variables ends here.


$filesCollectionInSourceDirectory=Get-ChildItem $filesFolderLoaction -File   

$uploadItemCount=1;
     
    #Extract the each file item from the folder.
    ForEach($oneFile in $filesCollectionInSourceDirectory)
    {            
               
            try
            {                            
          
                FileUploadToSPOnlineLibrary -SPOSiteURL $siteURL -SourceFilePath $oneFile.FullName -File $oneFile -TargetLibrary $listName -UserName $UserName -Password $Password
                
                $fileUploadingMessage=$uploadItemCount.ToString()+": "+$oneFile.Name; 
                Write-Host $fileUploadingMessage -BackgroundColor DarkGreen
                Write-Log $fileUploadingMessage

        $uploadItemCount++

        }
        catch
        { 
            $ErrorMessage = $_.Exception.Message +"in: " +$oneFile.Name
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 

        }

    }
    Write-Host "========================================================================"
    Write-Host "Total number of files uploaded: " $filesCollectionInSourceDirectory.Count 
    Write-Host "========================================================================"
    

 

Execute the above script successfully.

upload file to sharepoint document library using powershell

Revisit the SharePoint online “TestDocumentLibrary”, we can see that four files have been uploaded:

Upload files to SharePoint document library using PowerShell

Prerequisites to execute this script: PowerShell script to upload files to SharePoint

Need to place the below two DLLs in your script directory “Dependency Files” folder as below:

Upload files to sharepoint using PowerShell script CSOM

Pass the parameter (upload files to SharePoint using PowerShell): Change the value of the variable in the variables section

Below are the parameters for this script to run:

#Variables
$siteURL="Site URL"
$listName="Document Library Name"
$filesFolderLoaction=$directoryPathForFileToUploadLocation;
#Pass the local directory path where files are located. 
#Example:"C:\Temp\Files To Upload"
$userName = "YourSPOAccount@YourTenantDomain.com"
$password = "YourPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force
#Variables ends here.

Summary: upload files to SharePoint document library using PowerShell

Thus, in this article we have learned the below:

  • How to automatically upload files or documents to SharePoint Online using PowerShell CSOM code or script.
  • Using PowerShell upload files or documents to the SharePoint document library.

See Also: SharePoint Online PowerShell

You may also like the below SharePoint Online PowerShell tutorials:

 

PDF Download Image

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

About Post Author

2 comments on “In 2 steps instantly upload files to SharePoint document library using PowerShell CSOM”

Do you have a better solution or question on this topic? Please leave a comment