Deletion of contact record using Power Shell Script with fetchxml query in D365
$ CRMConnection = Get-CrmConnection -InteractiveMode
$ CRMConnection.BypassPluginExecution = $true
It seems like you are attempting to establish a connection to a Microsoft Dynamics CRM (Dynamics 365) instance using PowerShell and the Get-CrmConnection cmdlet.
However, it's important to note that the command you provided, $conn = Get-CrmConnection -InteractiveMode, seems to be incomplete. The -InteractiveMode parameter is typically used to prompt the user to interactively enter their CRM credentials.
To establish a connection to a Dynamics CRM instance in interactive mode and bypass plugin execution
Construct a query condition using Advanced Find.
Syntax
Remove-CrmRecord [-conn <CrmServiceClient>] [-CrmRecord] <PSObject> [<CommonParameters>]
Remove-CrmRecord [-conn <CrmServiceClient>] [-EntityLogicalName] <String> [-Id] <Guid> [<CommonParameters>]
![Powershell Interactive Login]()
Download Fetch XML query
![Download Fetch XML query]()
$fetchXml = @"
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="contact">
<attribute name="contactid" />
<order descending="false" attribute="fullname" />
<filter type="and">
<condition attribute="firstname" operator="like" value="%allam%" />
</filter>
</entity>
</fetch>
"@
$contacts = Get-CrmRecordsByFetch -conn $conn -Fetch $fetchXml;
# Retrieve ContactId from each contact record
for ($i= 1; $i -le $contacts.values.Count; $i++) {
$contactId = $contacts.values.contactid[$i]
Write-Host "ContactId: $contactId"
Remove-CrmRecord -conn $conn -EntityLogicalName contact -Id $contactId
}
This script retrieves a list of contacts from Dynamics 365 using FetchXML, which is a query language for Dynamics 365. The FetchXML query specified in the $fetchXml variable fetches contact records where the first name contains the substring "allam".
Once the contacts are retrieved, the script iterates over each contact record in the $contacts collection. For each contact, it retrieves the contactid attribute and removes the contact record from Dynamics 365 using the Remove-CrmRecord cmdlet.
However, there's a small correction needed in the loop. The index of the contact id should start from 0, not 1, since arrays are zero-indexed in PowerShell. Here's the corrected loop:
Check the connection $CRMConnection
![Deletion of Record using Power Shell Script with FetchXML Query in D365]()
![Deletion of Record using Power Shell Script with FetchXML Query in D365]()