SharePoint Online: PowerShell to Get List by URL

Requirement: PowerShell to Get List by URL in SharePoint Online

SharePoint Online: PowerShell to Get List by URL

You can get a list or library from its URL in SharePoint Online using the below PowerShell script:

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

#Function to Get List from URL
Function Get-ListByUrl([Microsoft.SharePoint.Client.ClientContext]$Ctx, $ListServerRelativeURL)
{
    #Get the Web from Context
    $Web = $Ctx.Web
    #Get the Root Folder of the List from Relative URL
    $ListFolder = $web.GetFolderByServerRelativeUrl($ListServerRelativeURL)
    $Ctx.Load($ListFolder.Properties)
    $Ctx.ExecuteQuery()
    
    #Get List Name from Root Folder's Properties
    $ListId = [System.guid]::New($ListFolder.Properties["vti_listname"].ToString())
    $List = $Web.Lists.GetById($ListId)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()
    Return $List
}
     
#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListServerRelativeURL = "/sites/marketing/Project Documents"
 
#Setup Credentials to connect
$Cred = Get-Credential

#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#call the function to get the List from URL
$List = Get-ListByUrl -Ctx $Ctx -ListServerRelativeURL $ListServerRelativeURL
Write-host $List.title

PnP PowerShell to Get a List from Its URL

PnP PowerShell handles this a bit differently! We just need the site relative URL of the list or library.

#Connect to Site
Connect-PnPOnline -Url "https://crescent.sharepoint.com/sites/marketing" -Interactive

#Get a List from site relative URL
$List = Get-PnPList -Identity "Lists/Projects"
Write-host $List.ItemCount

#Get a Document Library from its Site Relative URL
$Library = Get-PnPList -Identity "Branding"
Write-host $Library.ItemCount

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!

2 thoughts on “SharePoint Online: PowerShell to Get List by URL

Leave a Reply

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