PowerShellVSTSVSTS

Tip: Create a VSTS Tasks based on GIT repository code push (EVENT)

This article is to demo the available features (Service Hooks | Web Hooks) in VSTS and other possibilities to avoid manual interventions. You can think about any best fits your needs at your environment. For now, let me create a VSTS Work Item (Task) automatically for the repository code push – I would like to capture all the information as a task.

Simple Steps

  1. Node on Windows.
  2. Create a web server using express framework.
  3. Create a route with POST method and play with your needs.
  4. Add the route URL in service hooks wizard.
  5. Push the code from client machine which fires the event and calls PowerShell script to create a VSTS work item.

PowerShell Script to Create a VSTS Task

$Token = "Personal Access Token"
$accountName = "ACCOUNT NAME"
$projectName = "PROJECT NAME"
$Authentication = [Text.Encoding]::ASCII.GetBytes(":$Token")
$Authentication = [System.Convert]::ToBase64String($Authentication)
$Headers = @{
    Authorization = ("Basic {0}" -f $Authentication)
}
$Body = @(
    @{
        op    = "add"
        path  = "/fields/System.Title"
        value = "Created for the code push activity and no action required"
    }
    @{
        op    = "add"
        path  = "/fields/System.AssignedTo"
        value = "Chendrayan Venkatesan"
    }
    @{
        op    = "add"
        path  = "/fields/System.Description"
        value = "<b>Chen V - Task is Created - Code is Pushed - and auto close later.</B>"
    }
) | ConvertTo-Json
$Uri = "https://$accountName.visualstudio.com/$projectName/_apis/wit/workitems/`$task?api-version=4.1"
$Result = Invoke-RestMethod -Method Post -Uri $Uri -Headers $Headers -Body $Body -ContentType 'application/json-patch+json'
$Result

Now, here comes the Node.js (POST Route Listener)

var express = require('express');
var app = express();
var spawn = require('child_process').spawn, child;

app.get('/', function (request, response) {
    response.send('Hello World !')
});

app.post('/automate/vsts', function (request, response) {
    spawn('powershell.exe', [ 'C:\\Projects\\Hooks-Demo\\scripts\\CreateWIT.ps1' ]);
})

app.listen(80)
console.log('Your application is running on http://localhost:80')

Here comes the fun part – Set up Service Hooks and Choose Code Pushed!  When I push code to my repository I get a Task created for me

Output

Leave a Reply

Your email address will not be published. Required fields are marked *