SharePoint Online: How to Get a List using PowerShell?

Requirement: PowerShell to Get a List in SharePoint Online

SharePoint Online: PowerShell to Get a List

PowerShell is a powerful scripting language that can be used to automate tasks and manage your SharePoint Online environment. This guide will show you how to use PowerShell to get a list in SharePoint Online.

Here is how to access SharePoint Online list programmatically using PowerShell. Let’s get a list by title:

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

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/pmo" 
$ListName =  "Projects"
 
#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
 
    #Get the List
    $List = $Ctx.Web.lists.GetByTitle($ListName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()

    #Get Total number of Items in the List
    Write-host "Total Items: " $List.ItemCount
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

You can use this script to get any list or library from a given SharePoint Online site.

PnP PowerShell to Get a List in SharePoint Online

Let’s dive into how you can get a list in SharePoint Online using PnP PowerShell. The first thing you’ll need to do is connect to your SharePoint Online site using PowerShell and then use the PnP PowerShell cmdlet Get-PnPList to connect to the SharePoint Online list:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/pmo"
$ListName= "Projects"
  
#Connect to SharePoint Online site
Connect-PnPOnline $SiteURL -Interactive

Try {
    #sharepoint online get list using powershell
    $List = Get-PnPList $ListName -ThrowExceptionIfListNotFound -ErrorAction Stop
    
    #Get Total number of Items in the List
    Write-host "Total Items: " $List.ItemCount
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

To get all items in a SharePoint Online list, use: Get All Items from a SharePoint Online List using PowerShell

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

Your email address will not be published. Required fields are marked *