Remove Previous Versions

This script will loop through all lists in each site collection and remove previous versions of nintex workflows that are no longer running on an item. Its normally done by hand but with almost 300 sites I needed a way to do this efficiently. This can be scheduled to run during off hours on a regular basis. It runs quickly so runnung during the work day isn’t going to trip you up.

    This script removes workflow associations that are no longer in use on all lists on all sites on the named web application.
function SendeMail([string]$fileout)
	$smtpServer = "<your servers IP>" 

	$From = "<you>"
	$To = "<you>"

	$Subject = "Dead Versions Report"
	$Body = "Attached is a report of old versions of workflows that are no longer running and have been safely removed."

	    Send-MailMessage -To $To -Subject $Subject -Body $Body -SmtpServer $smtpServer -From $From -Attachments $fileout
     		$ErrorMessage = $_.Exception.Message
     		Write-Output $ErrorMessage 

$start = get-date
write-host "Started " $start
write-host "Please wait ..." -foregroundcolor green
 $outputFile = "PrevVersionsNotRunning.txt"

#Set the Web application URL

#Get the Web Application       
$WebApp = Get-SPWebApplication $WebAppURL
#Get all Site collections from the web application
$SPSites  = $WebApp.Sites

for($a = $SPSites.Count; $a -ge 0; $a--){
  	$SPWeb = $SPSites[$a].allWebs
	for($b = $SPWeb.Lists.Count; $b -ge 0; $b--){	
	   $SPList = $SPWeb.Lists[$b]
		$workflowAssociations = $SPList.WorkflowAssociations;
		if($null  -ne $workflowAssociations ){                  
                        for($i = $workflowAssociations.count; $i -ge 0; $i--){
                            if ($workflowAssociations[$i].Name -like "*Previous Version*" -and $workflowAssociations[$i].RunningInstances -eq 0) {                               
                                write-output $workflowAssociations[$i].name " on " $SPWeb.url  |out-file $outputFile -append
                                    }catch{write-output  $workflowAssociations[$i].name " FAILED on " $SPWeb.url  |out-file $outputFile -append }

$end = get-date	

write-host "Runtimes  " $start $end
SendeMail $outputFile

write-host "Total Time " $($end - $start)