SharePoint Online Automation – O365 – Create multiple items in a list using PowerShell CSOM

No comments

Here in this post, I will show how to create multiple list items in SharePoint online list using  PowerShell CSOM code programmatically.

PowerShell CSOM code to add multiple items:

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

$fileName = "Adding_Multiple_Items_Report"
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
$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
            
        }   
        
$logPath = $directoryPathForLog + "\" + $logFileName  
$isLogFileCreated = $False 

#DLL location
$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL
               
        } 

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

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

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   
    }   
} 

#variables region.
$siteURL="https://globalsharepoint.sharepoint.com/sites/TestSite/"
$spUserName="yourSPOAccount@globalsharepoint.onmicrosoft.com"
$password = "YourPassWord"
$spListName="Test List"
$numberOfItemsToCreate="5001"
#variables region end.

$securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
  
#Setup the Context

try
{
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($spUserName, $securePassword)
  

#Get the list
$spList = $ctx.Web.Lists.GetByTitle($spListName)
$ctx.Load($spList)
$ctx.ExecuteQuery()

#Loop thru to create the list items.
for($i=1; $i -le $numberOfItemsToCreate; $i++)
{
  $listItemCreationInformationInSPOnline = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
  $newListItemInSPOnline = $spList.AddItem($listItemCreationInformationInSPOnline)
  $newListItemInSPOnline["Title"] = "CustomItemNumberAddedThruCode_1_$($i)"
  $newListItemInSPOnline["CustomItemNumber"] = $i;
  $newListItemInSPOnline.Update()
  $ctx.ExecuteQuery()

  write-host "Item created in SP Online list: $spListName  CustomItemNumberAddedThruCode_$($i)"
}


}
catch 
{
  
    $errorMessage = $_.Exception.Message +"in adding mulitple items in SP Online list using CSOM PowerShell script";
    Write-Host $errorMessage -BackgroundColor Red
    Write-Log $errorMessage 
}
         
Write-Host "####################################################################"  -ForegroundColor Green 
Write-Host "The script execution has been completed!" -ForegroundColor Green 
Write-Host "###################################################################"

How to execute the above script?

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

DependencyDLLLocation

Change the value of the variable in the variables section like below:

#variables region.
$siteURL="Your SharePoint Site URL"
$spUserName="YourSPOAccount@globalsharepoint.onmicrosoft.com"
$password = "YourPassWord"
$spListName="Your List Name"
$numberOfItemsToCreate="5001"
#variables region end.

Execution:

NumberOfItemsToCreate

Output:

MultipleItemsAddedToSharePointList

Summary:

Here, in this article we have learned the below:

  • How to create list items using PowerShell in SharePoint Online.
  • How to create multiple list items in SharePoint online list using PowerShell script.