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
We can use PnP PowerShell to connect to SharePoint Online list, as:
#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
}