magritton
2/6/2019 - 11:27 PM

Run Workflow

Add-PSSnapin Microsoft.SharePoint.PowerShell  -erroraction silentlycontinue

$listName = "WorkflowExamples"
$workflowName = "WorkflowEmail"
$url = "https://xxxx/dept/109/109.14/BO/SS/DavidJWilliams"

$startDate = Get-Date
Set-SPLogLevel -TraceSeverity Verbose -EventSeverity Verbose

$web = Get-SPWeb -Identity $url

$path = "f:\temp\WorkflowRun.txt"
If (Test-Path $path){
	Remove-Item $path
}

$manager = $web.Site.WorkFlowManager
 
# Name of the list
$list = $web.Lists[$listName]
 
# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName($workflowName,"en-US")
 
$data = $assoc.AssociationData
$items = $list.Items
$assoc.AllowAsyncManualStart = $true
$assoc.AllowManual = $true

$item = $items[0]

$runningWorkflows = $item.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

if($runningWorkflows -eq $null)
{
	write-host "No workflows running..starting the workflow...." -BackgroundColor Yellow -ForegroundColor Black
	$wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
}

$runningWorkflows = $item.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

$runCount = 0
while($runningWorkflows -ne $null)
{
	$runCount = $runCount + 1
	write-host "workflow is still running..$runCount..on item id: $($item.ID)" -BackgroundColor Green -ForegroundColor Black
	$testItem = $list.GetItemById($item.ID)
	$runningWorkflows = $testItem.Workflows | Where-Object {($_.InternalState -eq "Running, HasNewEvents")}

	Start-Sleep -s 10
	
	if($runCount -eq 6 -or $runCount -eq 12 -or $runCount -eq 18 -or $runCount -eq 24)
	{
		#[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($runningWorkflows);
		$totalTime = $runCount * 10
		write-host "Workflow on item with ID $($item.id) has been running for $totalTime seconds" -BackgroundColor Blue -ForegroundColor White
		#$runningWorkflows = $null
	}
	
}#end while			
 
$manager.Dispose()
$web.Dispose()

Set-SPLogLevel -TraceSeverity High -EventSeverity Error
$endDate = Get-Date

Start-Sleep -s 15

$path = "F:\temp\temp.log"
If (Test-Path $path){
	Remove-Item $path
}

try
{
	Merge-SPLogFile -path $path -Overwrite -StartTime $startDate -EndTime $endDate
}
catch
{
    write-host "Error occured: $_"
}
#-Category "Information Policy Management"
notepad $path