Sunday 24 September 2017

Update Workflow Task List item from c# and Power-Shell

What if you need to update the task list item from code and not a step in the workflow ?
Will you simple write item.Update() ? - No
This will lock the task item and start giving error to users assigned to this task.

So, how to do it ? - Well SharePoint has given a special static class and it's methods to do this.
SPWorkflowTask.AlterTask  - click the link to read in details. 

A. Below C# code will use this function.

 //fields in the task list item to be updated
Hashtable data = new Hashtable();
data["Field1"] = "Value1";
data["Field2"] = "Value2";
data["Field3"] = "Value3";
 //add more above - if needed!!
SPWorkflowTask.AlterTask(itemTask, data, true);

#Note:   
1. Here, Field1, Field2 and Field3 are internal name of fields in the TaskList Item!! 
2. Value1, Value2 and Value3 are assumed to be string, please keep correct data type for your fields.
3. itemTask -> is the related task list item. You have to write logic to get this. In my case i get it with the help of URL.

 BSame Code in Power-Shell

The  above task can also be done in Power-Shell. Only two points have to taken care. 

1. How to use Hash Table in  Power-Shell - see sample code below
2. How to  write SPWorkflowTask.AlterTask in Power-Shell - sample code below
    #Note: This is very simple. For calling any static method in Power-Shell. 
                We write like this -> [ClassName]::FunctionName();

# Declare the hash table
$hashTableOfData = @{};

# Prepare data to be updated
$hashTableOfData.Add("Field1", "Value1"); 
$hashTableOfData.Add("Field2", "Value2");
$hashTableOfData.Add("Field3", "Value3");
                          
# Update - using the static method
[Microsoft.SharePoint.Workflow.SPWorkflowTask]::AlterTask($itemTask, $hashTableOfData, $true); 

No comments:

Post a Comment