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

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
}

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.