Getting Latest build in PS

Sometimes you need to get the latest successful build and get the download path for the artifact, for e.g. some 3 part tools or as an input for other build jobs.

First we define some variables about our setup.

$tfsServerURL = "HTTP://fabrikam:8080/tfs/defaultcollection"
$TFSProject = "My project"
$BuildDefinition = "MyAwesomeBuild"

Then construct the URL and get the build definition ID
$URL = "$($tfsServerURL)/$($TFSProject)"
$buildDefinitionID = (Invoke-RestMethod -Uri ($URL + '/_apis/build/definitions?api-version=2.0&name=' + $BuildDefinition) -Method GET -UseDefaultCredentials).value.id

With the definition ID in hand, we get the URI of the latest succeeded build.
$LatestBuildURI= $URL + '/_apis/build/builds?definitions=' + $buildDefinitionID + '&statusFilter=completed&resultFilter=succeeded&$top=1&api-version=2.0'

Then we need to get the build itself.
$Build = (Invoke-RestMethod -Uri $LatestBuildURI -Method GET -UseDefaultCredentials).value

If we need to get the artifacts we can also ask for this.
$ArtifactsURI = $URL + ‘/_apis/build/builds/’ + $Build.Id + ‘/artifacts?api-version=2.0’

$ArtifactPath = (Invoke-RestMethod -Uri $ArtifactsURI -Method GET -UseDefaultCredentials).value.resource.data

The full script:

$tfsServerURL = "HTTP://fabrikam:8080/tfs/defaultcollection"
$TFSProject = "My project"
$BuildDefinition = "MyAwesomeBuild"

$URL = "$($tfsServerURL)/$($TFSProject)"
#Get ID of Builddefinition
$buildDefinitionID = (Invoke-RestMethod -Uri ($URL + '/_apis/build/definitions?api-version=2.0&name=' + $BuildDefinition) -Method GET -UseDefaultCredentials).value.id

#Get the latest completed succeeded Build
$LatestBuildURI= $URL + '/_apis/build/builds?definitions=' + $buildDefinitionID + '&statusFilter=completed&resultFilter=succeeded&$top=1&api-version=2.0'

#Get the specific Build
$Build = (Invoke-RestMethod -Uri $LatestBuildURI -Method GET -UseDefaultCredentials).value

#Get the builds artifacts
$ArtifactsURI = $URL + '/_apis/build/builds/' + $Build.Id + '/artifacts?api-version=2.0'

#Get artifact Path
$ArtifactPath = (Invoke-RestMethod -Uri $ArtifactsURI -Method GET -UseDefaultCredentials).value.resource.data

Author: KimC

TFS admin and deployment fellow

One thought on “Getting Latest build in PS”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s