Home
> Power Platform > [Code Snippet] Xrm.Data.Powershell | Get-CrmRecordsByFetch
[Code Snippet] Xrm.Data.Powershell | Get-CrmRecordsByFetch
In this article lets see how to execute the Get-CrmRecordsByFetch operation in PowerShell using Microsoft.Xrm.Data.PowerShell library.
What is Microsoft.Xrm.Data.PowerShell
- The Microsoft.Xrm.Data.Powershell library is a PowerShell module that provides cmdlets for working with Microsoft Dynamics 365 and Dataverse data.
- The library provides cmdlets for performing CRUD operations (Create, Retrieve, Update, and Delete) on entities in Dynamics 365 and Dataverse.
- It also provides cmdlets for working with metadata, running FetchXML queries, and executing custom actions and workflows.
In this article, I will provide the code snippet for Get-CrmRecordsByFetch operation. Get-CrmRecordsByFetch operation retrieves CRM records by using FetchXML query.
Scenario:
I need to fetch ‘User’ table records, if either a ‘Domain Name’ or ‘Primary Email’ matches with the passed value.
Following is the FetchXML.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="systemuser">
<attribute name="systemuserid" />
<filter type="and">
<filter type="or">
<condition attribute="internalemailaddress" operator="eq" value="user@email.com" />
<condition attribute="domainname" operator="eq" value="user@uname.com" />
</filter>
</filter>
</entity>
</fetch>
Now lets see how to execute the Fetchxml using Get-CrmRecordsByFetch operation.
Code Snippet:
Following code executes the FetchXML and read the response.
function Get-User-By-Email-or-DomainName{
param(
[Parameter()] [String] [AllowEmptyString()]$filterValue,
[Parameter(Mandatory)] [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]$conn
)
$matchedUser = $null
$fetchxml = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='systemuser'>
<attribute name='systemuserid' />
<filter type='and'>
<filter type='or'>
<condition attribute='internalemailaddress' operator='eq' value='$filterValue' />
<condition attribute='domainname' operator='eq' value='$filterValue' />
</filter>
</filter>
</entity>
</fetch>
"@
Write-Host "Request XML - "$fetchxml
$records = Get-CrmRecordsByFetch -Fetch $fetchxml-conn $conn
try{
$json = ConvertTo-Json $records # Optional step to print the Response in json format
Write-Host "Response - $json"
# Loop through the matching records and gets the first record.
if($records -and $records.CrmRecords){
$matchedUser = $records.CrmRecords[0]
# Read the column value
$systemUserId = $matchedUser.systemuserid
}
}
catch {
Write-Host "An error occurred in Get-User-By-Email-or-DomainName: $($_.Exception.Message)"
}
return $matchedUser
}
:)
Categories: Power Platform
FetchXML, Get-CrmRecordsByFetch, PowerShell
Comments (0)
Trackbacks (0)
Leave a comment
Trackback