This is a quick blog post for a fun PowerShell script I got to write today. My client asked me to make a listing of all instances of a particular workflow currently running on one of our SharePoint farms. Since we have dozens of SharePoint lists spread out across numerous sub-sites on this farm I decided to tackle the request with PowerShell.
Here is a quick overview of what the scrip accomplishes. First I get a reference to the site collection in question. Next I get the workflow template from the name of the workflow I’m checking for. Next I search all webs within the site collection and all lists within each web. I filter the lists for any workflow associations with a BaseId matching my workflow template Id while also having at least 1 running instance. Once I know there are running instances on this list I can then loop through all items in the list checking for workflows that are in the “Running” state. I then output the SPWeb name, SPList name, and SPListItem name into a delimited output.
On a side note you may notice that I use $($variable.property) in my “write-output…” command. I do this so that the property values are evaluated first before being passed to the the output stream. If you attempt $variable.property you’ll most likely end up with a default value for $variable (typically ToString()) followed by “.property” which is not the intended result.
Download Script
Click here for a copy of this script off my SkyDrive.
*Note: As I’m currently very busy with SharePoint Saturday Columbus tasks this script is just in draft form so no recursive traversal of site hierarchy, input parameters, comments, etc.
$workflowNameToCheck = "My Sample Workflow"
$url = "http://SharePointDemo"
$spSite = new-object Microsoft.SharePoint.SPSite($url)
$spWeb = $spSite.OpenWeb()
$workflowBase = $spweb.WorkflowTemplates | where {$_.Name -eq $workflowNameToCheck}
$spWeb.Dispose()
foreach($spWeb in $spSite.AllWebs)
{
for($i = 0; $i -lt $spWeb.Lists.Count; $i++)
{
$spList = $spweb.Lists[$i]
$assoc = $spList.WorkflowAssociations | where {$_.BaseId -eq $workflowBase.Id.ToString() `
-and $_.RunningInstances -gt 0}
if($assoc -ne $null)
{
foreach($item in $spList.Items)
{
if(($item.Workflows | where {$_.InternalState -eq "Running"}) -ne $null)
{
write-output "$($spWeb.Name) | $($spList.Title) | $($item.Name)"
}
}
}
}
$spWeb.Dispose()
}
$spSite.Dispose()
Conclusion
This script (very much in draft form) checks for running instances of a given workflow within a site collection. After writing this script today I felt that this is probably a common search for some people so I hope you can glean some useful information from it. If you find it useful or have any questions feel free to let me know. Enjoy!
-Frog Out
Monday, July 12, 2010 10:31 PM