SharePoint – Running a CAML Query in Powershell

Whenever you want to retrieve data from a SP list in a fast way. Especially when you are dealing with a large list.

There is no way around the ‘CAML’ queries, for fast results.

This example gives you an idea on how to build the query.

We are running the query to search for a Text string “Attachment.pdf” in a TEXT Field of the List.

if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)
 Add-PSSnapin Microsoft.SharePoint.PowerShell;
$WebUrl = "http://YourSide/sites/SiteCollectionName"

#Get the Web & Lists to upload the file
$web = Get-SPWeb $WebURL

# $WebUrl=$site.OpenWeb()
$list = $web.Lists["Your_BigListName"]

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 20

$Ref = "My Attachment.pdf"

$sQry = '<Where><Contains><FieldRef Name="Body"/><Value Type="Note">' + $Ref + '</Value></Contains></Where>'

$caml = $sQry

$spQuery.Query = $caml

$listItems = $list.GetItems($spQuery)
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
Write-Host $item.ID "-" $item.Title "-" $item.body
Echo ""
while ($spQuery.ListItemCollectionPosition -ne $null)


To get to know the CAML query syntax best use the famous CAML builder Tool.

Look here for more interesting Tools !


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: