If you are looking to automate cloning a build in VSTS using Powershell, you can use the following script (made in line with this documentation).
You will need to change:
$buildToCloneName
, $newBuildName
, $user
, $accessToken
, $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
and $env:SYSTEM_TEAMPROJECTID
for it to work for you.
$env:SYSTEM_TEAMPROJECTID
is the Team Project where the build is.
Powershell Script:
Clear-Host
$buildToCloneName = "Build 1"
$newBuildName = "Build 1 - Clone"
$user = "[email protected]"
$accessToken="4df31252fqt...PAT...."
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI = "https://mycompany.visualstudio.com/"
$env:SYSTEM_TEAMPROJECTID = "MyProject"
"Getting all bulid definitions"
$allSuitesBuildUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$($env:SYSTEM_TEAMPROJECTID)/_apis/build/definitions?api-version=2.0"
$allSuitedBuilds = Invoke-RestMethod -Uri $allSuitesBuildUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
"Builds Found - Finding Match for $buildToCloneName"
$buildWeWant = {}
foreach($buildDetails in $allSuitedBuilds.value)
{
"Checking Build"
$buildDetails."name"
if($buildDetails."name" -like $buildToCloneName)
{
$xoutputname = $buildDetails."name"
"YES! Got Build $xoutputname"
$buildWeWant = $buildDetails
break
}
else
{
"Nope!"
}
}
$buildId = $buildWeWant."id"
[int]$buildIdTest = $null
if(![int]::TryParse($buildId, [ref]$buildIdTest))
{
throw [Exception] "ERROR: NO BUILD ID FOUND"
}
"Getting the exact definition for the build"
# You can see this in the browser using https://mycompany.visualstudio.com/ProjectWhereBuildIs/_apis/build/definitions/{BuildNumber}?api-version=2.0
$thisBuildDefUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$($env:SYSTEM_TEAMPROJECTID)/_apis/build/definitions/" + $buildId + "?api-version=2.0"
$thisBuildDefUrl
$thisBuildDef = Invoke-RestMethod -Uri $thisBuildDefUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
"Assigning a new name"
$thisBuildDef.Name = $newBuildName
"Creating a clone build with name $newBuildName"
$defAsJson = $thisBuildDef | ConvertTo-Json -Depth 100
$newBuildDefUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$($env:SYSTEM_TEAMPROJECTID)/_apis/build/definitions?api-version=2.0"
$newBuildDef = Invoke-RestMethod -Uri $thisBuildDefUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method Post -Body $defAsJson -ContentType "application/json" -ErrorAction Stop
$newBuildDefAsJson = $newBuildDef | ConvertTo-Json -Depth 100
$newBuildDefAsJson
"New Build Created"
$newBuildDef.Name