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 - Lets 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
$WebURL="http://intranet.crescent.com/"
$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 = "@
<Where>
    <Eq>
        <FieldRef Name='Status' />
        <Value Type='Choice'>Active</Value>
    </Eq>
</Where>"

#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
CAML Query to Get List Items from SharePoint using PowerShell CAML Query to Get List Items from SharePoint using PowerShell Reviewed by Unknown on April 04, 2017 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.