Functions/Audit/Get-CdsAuditHistory.ps1
<#
.SYNOPSIS Retrieve audit for given record. #> function Get-CdsAuditHistory { [CmdletBinding()] param ( [Parameter(Mandatory = $false, ValueFromPipeline)] [Microsoft.Xrm.Tooling.Connector.CrmServiceClient] $XrmClient = $Global:XrmClient, [Parameter(Mandatory = $true, ValueFromPipeline)] [Microsoft.Xrm.Sdk.EntityReference] $RecordReference ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); } process { $auditLogs = @(); $retrieveRecordChangeHistoryRequest = New-Object -TypeName Microsoft.Crm.Sdk.Messages.RetrieveRecordChangeHistoryRequest; $retrieveRecordChangeHistoryRequest.Target = $RecordReference; $retrieveRecordChangeHistoryReponse = Protect-CdsCommand -ScriptBlock { $XrmClient.Execute($retrieveRecordChangeHistoryRequest) }; foreach ($auditDetail in $retrieveRecordChangeHistoryReponse.AuditDetailCollection.AuditDetails) { foreach ($attribute in $auditDetail.NewValue.Attributes) { $auditRecord = $auditDetail.AuditRecord; $attributeName = $attribute.Key; $oldValue = ""; if ($auditDetail.OldValue.Contains($attributeName)) { if ($auditDetail.OldValue.FormattedValues.ContainsKey($attributeName)) { $oldValue = $auditDetail.OldValue.FormattedValues[$attributeName]; } else { $oldValue = $auditDetail.OldValue[$attributeName]; } } $newValue = ""; if ($auditDetail.NewValue.Contains($attributeName)) { if ($auditDetail.NewValue.FormattedValues.ContainsKey($attributeName)) { $newValue = $auditDetail.NewValue.FormattedValues[$attributeName]; } else { $newValue = $auditDetail.NewValue[$attributeName]; } } $hash = @{}; $hash["Object"] = $auditRecord.FormattedValues["objecttypecode"]; $hash["Id"] = $auditRecord["objectid"].Id; $hash["Key"] = $RecordReference.Id; $hash["AttributeName"] = $attributeName; $hash["CreatedOn"] = $auditRecord.FormattedValues["createdon"]; $hash["User"] = $auditRecord["userid"].Name; $hash["Operation"] = $auditRecord.FormattedValues["operation"]; $hash["Action"] = $auditRecord.FormattedValues["action"]; $hash["OldValue"] = $oldValue; $hash["NewValue"] = $newValue; $auditLog = New-Object PsObject -Property $hash; $auditLogs += $auditLog; } } $auditLogs; } end { $StopWatch.Stop(); Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch; } } Export-ModuleMember -Function Get-CdsAuditHistory -Alias *; |