How can I fire a query on User Profiles in the SP 2013
Question
I have to fetch the User Profiles list with filters like - First_Name starts with A or Department_Name = "Test" and get the count of those users and all users without Search Service/KQL. Simply I have to fire an query (Like- SQL/CAML) to get the list of users profiles. I have to implement this in the Custom WebPart.
Solution
Profile Manager Search method searches 'FirstName', 'LastName', 'PreferredName', 'UserName', 'Office', 'Title', 'Department', 'WorkEmail', 'SPS-SipAddress', and 'AccountName'. The method performs a "begins with" sort of search, so you get a match when the search pattern strings match the first characters in any of the searchable properties.
This is how you can search for anything starting with "A" programmatically:
using (SPSite site = new SPSite("https://spsite.yourcompany.com/"))
{
SPServiceContext context = SPServiceContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(context);
string searchPattern = "A";
ProfileBase[] EmpSrchResults = profileManager.Search(searchPattern);
foreach (ProfileBase EmpProfile in EmpSrchResults)
{
Console.WriteLine(EmpProfile.DisplayName);
}
}
Another alternative is to use PowerShell to get all your results filtered at once and write the results to a CSV file as shown below :
$siteUrl = "https://spsite.yourcompany.com/"
$outputFile = "D:\Shared\CSVProfiles\$(get-date -uformat '%Y-%m-%d-%H-%M-%S-%p').csv"
$serviceContext = Get-SPServiceContext -Site $siteUrl
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$profiles = $profileManager.GetEnumerator() | Sort -property @{Expression={$_["FirstName"]}} | ?{$_["FirstName"] -like "A*"}
#Following line will give you the count of the filtered results
$count=$profiles.Count
Write-Host "Exporting profiles"
$collection = @()
foreach ($profile in $profiles)
{
$profileData = "" | select "AccountName","FirstName", "LastName"
$profileData.AccountName = $profile["AccountName"].Value
$profileData.FirstName = $profile["FirstName"].Value
$profileData.LastName = $profile["LastName"].Value
$collection += $profileData
}
$collection | Export-Csv $outputFile -NoTypeInformation
Write-Host "Profiles Created Successfully"