Archive

Posts Tagged ‘Powershell’

Use PowerShell to call TFS 2015 REST API’s


Few months ago, I was helping a client upgrading from TFS 2010 to 2015. After the upgrade, we were getting a message that says “This feature cannot be used until you configure it for this team project”.

Long story short, I had to upgrade the process template for over 77 team projects. Luckily they were all created using the Agile template 🙂 The process involves running some commands for the collection and others for each team project. That’s when I decided to script it with PowerShell.

In this post, I will show how to use Powershell to call the TFS 2015 REST API. Let me know in the comment section if you are interested in the script to upgrade the process template.

Show me the code

I am using the “Get list of team project” API which is listed at https://www.visualstudio.com/en-us/docs/integrate/api/tfs/projects


$tfsUrl = 'http://tfsUrl:8080/tfs/'
$collectionName = 'DefaultCollection'
$collectionUrl =  "$($tfsUrl)$($collectionName)"
# Construct the Get list of team projects url
$getProjectsUrl = "$($collectionUrl)/_apis/projects/?api-version=1.0"

# Call the REST API using Invoke-RestMethod. -UseDefaultCredentials for using windows authentication
$json = Invoke-RestMethod -UseDefaultCredentials -uri $getProjectsUrl
$formatedJson =  $json | Format-List
Write-Output $formatedJson

The value field contains the data we need. It is just a matter of extracting the project names from the value field

$tpNames = $json.value | select name
Write-Output $tpNames

The above snippet only shows you a list of project names on the screen. Lets do something more interesting. Let’s say we want create a new team for each team project in a collection and call it Database Team

# Create team API
$createTeamUrl = "$($collectionUrl)/_apis/projects/{0}/teams?api-version=2.2"
#Json that contains the data to be POSTed
$Body = @{
            name = "Database"
            description = "Database Team"
        }

# for each team project, create a team called Database by doing a post request to the create team api
$json.value.ForEach({
    Invoke-RestMethod -Method Post -UseDefaultCredentials -uri ($createTeamUrl -f $_.name) -Body (ConvertTo-Json $Body) -ContentType "application/json"
})

Conclusion

It is really convent and powerful to use Powershell or any other scripting language to TFS’s REST API. To learn more about TFS’s REST APIs visit https://www.visualstudio.com/en-us/docs/integrate/api/overview

About Lajak Technologies

A consulting firm in Ottawa, Ontario that provides services related to Microsoft technologies, Team Foundation Server, DevOps practices, security and more. Contact us today to help you solving your complex software problems. Visit us at http://www.lajak.com.

 

 

Advertisements