I have craeted a powershell script to terminate all the corrupted workflows which are older than 4 hours. But I think it is not looking only for the running workflows. It is looking for all the workflow instances. Also the workflow instances which are already terminated. How can I change the script to just terminate workflowinstances which are running?
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
###########################
# Main
###########################
cls
$spSite = Get-SPSite "https://portal.myCompany.net/teams/siterequests/" # SiteCollection
$spWeb = $spSite.OpenWeb() # Evt. (sub)Web kan hier
for($i = 0; $i -le $spWeb.Lists.Count;$i++)
{
foreach ($item in $spWeb.Lists[$i].Items)
{
foreach ($workflow in $item.Workflows)
{
if(($workflow | where {$_.InternalState -ne "Completed"}) -ne $null) #Error Occurred
{
$CurrentDateTime = Get-Date
$ExpiredDateTime = ($workflow.Created.ToLocalTime()).AddHours(4)
if($CurrentDateTime -gt $ExpiredDateTime)
{
Write-Host ("Terminate corrupted workflow. List: {0}, item {1}, workflow status: {2}, workflow started: {3}" -f $spWeb.Lists[$i].Title, $item.Title, $workflow.InternalState, $workflow.Created.ToLocalTime()) -BackgroundColor Black -ForegroundColor Yellow
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($workflow)
}
}
}
}
}
$spWeb.Dispose()
$spSite.Dispose()
This is for example on of the corrupted workflow instances. Like these I would like to terminate in my powershell script. BUT I would like to terminate only the corupted running instances. Not the instances which already terminated.