Tuesday 23 July 2013

Remove workflow

Previously I showed you how to add a workflow and task list to all of your subsites through a powershell script, now let’s say what was done must also be able to be undone. So naturally here’s a powershell script to remove your Workflow and task list from all sub webs.

Section One (Set up)

#get the site url to deploy workflow to
param($siteUrl=$(read-host "Please provide web app url of the list to be delete (EG:'http://Wingtip'):"))

#ensure that user provided site url parameter
if($siteUrl -eq $null -or $siteUrl -eq '')
    throw "You must specify your server name. Value provided was null/empty."

#function to load SharePoint Powershell snap in
function LoadSharePointPowerShellEnviroment
 #clear the screen of pevious output
 write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
 Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
 Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green

#call sharepoint plugin function

Section Two(Declare constants)

#get site using parameter
$site = Get-SPSite($siteUrl)

#Name of task list to delete
$listName = "Approval Tasks"

#approval workflow ID, specified in elements file of workflow
$APPROVALWORKFLOWID = [GUID]("64f076cb-a5f8-4ee7-9ef4-54820d291886");
Section Three(remove workflow function)
#remove workflow function
function RemoveAssociation($web, $listName)
      #library the workflow is runnion on
      $listInstance = $web.Lists.TryGetList($listName)
      #make sure the library exists
      if($listInstance -ne $null)
            #get the number of workflows running on library
            $i = $listInstance.WorkflowAssociations.Count - 1
            While($i -gt -1)
                  #if workflow is ours, and it has 0 running then remove it.
                  if($listInstance.WorkflowAssociations[$i].BaseTemplate.Id.Equals($APPROVALWORKFLOWID) -and
                     $listInstance.WorkflowAssociations[$i].RunningInstances -eq 0)
                        Write-Host "Removing Workflow " $listInstance.WorkflowAssociations[$i].Name "From" $listName -ForegroundColor DarkGreen
      $listInstance = $null

Section Three(traverse all webs and remove list)

#itterate through all subsites
foreach ($web in $site.AllWebs)
      #get the list you whish to delete
      $listToDelete = $web.Lists.TryGetList($listName)
      #if the list exists delete it
      if($listToDelete -ne $null)
            Write-Host $listToDelete.RootFolder $listName " has been deleted" -ForegroundColor Green
      #remove the workflow from libraries
      RemoveAssociation $web "Pages"
      RemoveAssociation $web "Images"
      RemoveAssociation $web "Documents"


Write-Host "Script Complete" -ForegroundColor Blue