How to restore Dynamics CRM entity from audit log

Eventually almost everyone face the situation when you removed something that shouldn't be removed. There is no built-in recycle bin inside Dynamics CRM. Restoring database to specific state isn't right thing to do for sure, because of several reasons:

  • It is resource intensive.
  • You may not have so old backup.
  • I doubt you can mime CRM ORM that good. Simple 'select into' may not workout well.
  • I prefer to avoid direct database interaction where it is possible over SDK. It is always more safe.

The main article with a few code snippets that I took as a base for that process you could find here - Recover your deleted CRM data and recreate them using CRM API. Having audit enabled for that entity prior deletion is required. Here are step-by-step guide how to do it easily with Handy.Crm.Powershell.Cmdlets:

  1. Find related change record in Audit Summary View. Pay attention to filters on columns Entity and Operation. Audit Summary View

  2. Determine GUID of deleted entity. Click on record. Note that if you have DevErrors off in yours CRM webconfig, you can take GUID also from the address bar Deleted entity

  3. Execute next script

Import-Module Handy.Crm.Powershell.Cmdlets
Import-Module Handy.Crm.Extensions.Powershell.Cmdlets

# Creating connection to CRM
$con = Get-CRMConnection -ConnectionString "Url=https://org.crm.local; Username=crm\Administrator; Password=Passw0rd; Timeout=0:2:0"

# Retrieving latest entity change
$retrieveRecordChangeHistoryParameters['Target'] = Get-CRMEntityReference -EntityName 'account' -Id DA0A296A-B916-476D-9671-8C481719DE62
$response = Invoke-CRMOrganizationRequest -Connection $con -RequestName 'RetrieveRecordChangeHistory' -Parameters $retrieveRecordChangeHistoryParameters

$change = $response.Results['AuditDetailCollection'].AuditDetails | ? { $_.NewValue -eq $null }

# Creating entity from latest change snapshot

$createParameters['Target'] = $change.OldValue
$response2 = Invoke-CRMOrganizationRequest -Connection $con -RequestName 'Create' -Parameters $createParameters

It has never been so easy. You don't need to write any .net code. Only basic knowledge of CRM and a few lines of PowerShell. That's the power of perfectly sharpened tools for operation.