SharePoint Online: Get a Document Library using PowerShell

Requirement: Get a Document Library in SharePoint Online using PowerShell.

sharepoint online powershell get document library

SharePoint Online: Get a Document Library using PowerShell

When working with PowerShell and SharePoint Online, there may be times when you need to get a document library. There are many ways to interact with SharePoint Online. In this blog post, we’ll look at how to get a document library using PowerShell. This can be useful for automating tasks or reporting purposes. Let’s get started!

Here is the PowerShell to Get SharePoint Online document library:

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

#Variables
$SiteURL = "https://crescent.sharepoint.com/Sites/Marketing"
$DocLibraryName="Documents"

#Setup 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)
 
    #sharepoint online get a document library powershell
    $DocLibrary = $Ctx.Web.Lists.GetByTitle($DocLibraryName)
    $Ctx.Load($DocLibrary)
    $Ctx.ExecuteQuery()

    Write-host "Total Number of Items in the Document Library:"$DocLibrary.ItemCount
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

PnP PowerShell to get a document library in SharePoint Online:

To get a document library in the SharePoint Online site, Here is the PnP PowerShell script:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Documents"

#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Interactive

#sharepoint online powershell get document library
$DocumentLibrary = Get-PnPList -Identity $LibraryName

#Get Number of Items the Document Library
Write-host $DocumentLibrary.ItemCount

This script gets the document library and returns a number of items from the library. To get all document libraries in SharePoint Online, use: SharePoint Online: PowerShell to Get Document Libraries

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

Leave a Reply