SOLUTION FOR AUTOMATIC CLEANUP OF WORKLFOW HISTORY

Issue

By default, SharePoint runs a daily Workflow Auto Cleanup job to permanently delete workflow instances and related task entries that still exist 60 days after a workflow is completed or cancelled. Workflow history items themselves are not deleted, but the entry point to view them on the status page for a particular instance will no longer be available.

Solution

1. Disable the SharePoint auto cleanup jobDisable preservation of workflow history.

2. Increase the number of days the auto cleanup job will delete history: The following PowerShell script will help you to apply for each SharePoint site:

add-pssnapin "microsoft.sharepoint.powershell" -ea 0
function Set-SPListWorkflowAssocationCleanup {
param (
[string] $WebUrl = $(Read-Host -prompt "Enter a Url"),
[int32] $CleanupDays = $(Read-Host -prompt "Enter the number of Cleanup Days"),
[switch] $ReportOnly = $true
)
$web = Get-SPWeb $WebUrl;
if ($web -eq $null) { Write-Error -message "Error: Web Not Found" -category InvalidArgument }
else
{ $c = $web.Lists.Count - 1;
for ($i=0; $i -le $c; $i++)
{
$list = $web.Lists[$i];
$message = "List: " + $list.Title
Write-Verbose -message $message -verbose
[Microsoft.SharePoint.Workflow.SPWorkflowAssociation[]] $wfaMods = @();
foreach ($wfa in $list.WorkflowAssociations)
{
$message = "Found WA for " + $wfa.Name + " with AutoCleanupDays set to " + $wfa.AutoCleanupDays
Write-Verbose -message $message -verbose
if ($ReportOnly -eq $false)
{ $wfa.AutoCleanupDays = $CleanupDays; $wfaMods = $wfaMods + $wfa;}
}
if ($ReportOnly -eq $false)
{
foreach ($wfa in $wfaMods)
{
$wfa.AutoCleanupDays = $CleanupDays;
$list.WorkflowAssociations.Update($wfa);
$message = "Setting AutoCleanupDays for " + $wfa.Name + " to " + $CleanupDays
Write-Verbose -message $message -verbose
}
}
}
}
}
Set-SPListWorkflowAssocationCleanup -WebUrl "<site_url>" -CleanupDays <number_of_days> -ReportOnly:$false

Enjoy!!!
Nhat Phan