PowerShell-CAML SPQuery to Filter List Items based of Person or Group Field Value

Requirement:
In a project tracking SharePoint list, want to quickly get the list of projects where a particular user is listed as Project Manager – person or group (People picker) field.

Solution: Use SPQuery with PowerShell as in the below example.

PowerShell to Filter List Items based on Person or Group Field:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration parameters
$SiteURL = "https://portal.crescent.com/projectpipeline/"
$ListName = "Projects"
$FieldName= "ProjectManager"
$UserAccount="Crescent\Omar"

#Get the User Account
$User = Get-SPUser -Identity $UserAccount -Web $SiteURL

#Query to filter List Items which contains user account
$SPQuery = new-object Microsoft.SharePoint.SPQuery
$Query = "<Where><Eq><FieldRef Name='ProjectManager' LookupId='TRUE'/><Value Type='User'>$($User.ID)</Value></Eq></Where>"
$SPQuery.Query=$Query

#Get site and List objects
$web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)

#Filter List Items by Query
$ListItems = $List.GetItems($SPQuery)
foreach($item in $ListItems)
{
    write-host $Item["ProjectName"]
}
write-host "Total Number of Projects Found:" $ListItems.Count

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

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