CAML Query to Get List Items from SharePoint using PowerShell

CAML stands for Collaborative Application Markup Language. It’s an XML based query language used to query against data in SharePoint

How to use CAML query in PowerShell?

Basically, we create a CAML query and pass a SPquery object to retrieve filtered list items from the object. Here is a basic example for how to use CAML query in PowerShell – let’s get all “Active” Projects from the projects list.

SharePoint PowerShell CAML Query Example

Here is how to use CAML query in PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set config variables
$ListName ="Projects"

#Get Web and List Objects
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]

#Define the CAML Query
$Query = New-Object Microsoft.SharePoint.SPQuery
$Query.Query = "@
        <FieldRef Name='Status' />
        <Value Type='Choice'>Active</Value>

#Get List Items matching the query
$ListItems = $List.GetItems($Query)

Write-host "Total Number of Items: "$ListItems.count

#Loop through Each Item
ForEach($Item in $ListItems) 
    #Do something
    Write-host $Item["Title"]

Why we should use CAML to filter list items?
Well, we can filter list items as:

$ListItems = $List.Items | Where {$_["Status"] -eq "Active"}

However, Using CAML is highly recommended. Using CAML query to get items from SharePoint list or document library benefits with greater performance!

SharePoint CAML Query Builder Tool
There are tools available to generate CAML Query. My favorite CAML query builders are: U2U CAML Query Builder and CAML Designer 2013 which works with both SharePoint On-premises and SharePoint Online.

Here is my another post for SharePoint Online on How to use CAML query with PowerShell: SharePoint Online CAML Query in PowerShell

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