1

I would like to add a schedule on a build definition taken from TFS REST API using PowerShell (add schedule to $buildDef variable on code example).

I get the build definition doing an API request but I'm not able to create a schedule for each week as trigger. I have used below Api for updating the trigger schedule.

$buildDef = Invoke-RestMethod -Method Get -UseDefaultCredentials -ContentType application/json -Uri $TfsBuildDefinitionUri

Any help would be appreciated as I am not able to get it done. Thanks!!

1
  • 1
    Thanks for your help @PatrickLu-MSFT but finally I found the way to create a trigger on a build definition from PowerShell. Commented Dec 9, 2019 at 10:16

3 Answers 3

0

First of all , you have to get the build definition of the ADO build by utilizing below method:

GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1

With additional parameters:

GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?revision={revision}&minMetricsTime={minMetricsTime}&propertyFilters={propertyFilters}&includeLatestBuilds={includeLatestBuilds}&api-version=5.1

Then it would give you an array of **[BuildTrigger][1]** then you have to update the schedule of DefinitionTriggerType.

schedule

A build should be started on a specified schedule whether or not changesets exist.

Here is a sample code for updating triggers of a build:

$definitionToUpdate = Invoke-RestMethod -Uri "$($collection)$($project.name)/_apis/build/definitions/$($definition.id)" -Method GET -Header $header
    $trigger = $definitionToUpdate.triggers | Where {$_.triggerType -eq 'continuousIntegration'}

    if ($trigger) {
        $trigger.branchFilters = $branchNames | % {"+refs/heads/$_/*"}
        Invoke-RestMethod -Uri "https://devops.domain.com/Collection/Project/_apis/build/definitions/$($definition.id)?api-version=5.0" -Method PUT -ContentType application/json -Body ($definitionToUpdate | ConvertTo-Json -Depth 10) -Header $header
    }

You can refer this thread for further reference, Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you already got the build definition. Then you just need to use Definitions - Update Rest API to update

PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?secretsSourceDefinitionId={secretsSourceDefinitionId}&secretsSourceDefinitionRevision={secretsSourceDefinitionRevision}&api-version=5.0

In the request body, there is a BuildTrigger represents a trigger for a buld definition. Which is an array[]. It contain the schedule string : A build should be started on a specified schedule whether or not changesets exist.

Body sample for your reference:

Content-Type: application/json
{
  "id": 29,
  "revision": 1,
  "name": "myFavoriteDefinition",
  "definitionType": "build",
  "documentQuality": "definition",
  "queue": {
    "id": 1
  },
  "build": [
    {
      "enabled": true,
      "continueOnError": false,
      "alwaysRun": false,
      "displayName": "Build solution **\\*.sln",
      "task": {
        "id": "71a9a2d3-a98a-4caa-96ab-affca411ecda",
        "versionSpec": "*"
      },
      "inputs": {
        "solution": "**\\*.sln",
        "msbuildArgs": "",
        "platform": "$(platform)",
        "configuration": "$(config)",
        "clean": "false",
        "restoreNugetPackages": "true",
        "vsLocationMethod": "version",
        "vsVersion": "latest",
        "vsLocation": "",
        "msbuildLocationMethod": "version",
        "msbuildVersion": "latest",
        "msbuildArchitecture": "x86",
        "msbuildLocation": "",
        "logProjectEvents": "true"
      }
    },
    {
      "enabled": true,
      "continueOnError": false,
      "alwaysRun": false,
      "displayName": "Test Assemblies **\\*test*.dll;-:**\\obj\\**",
      "task": {
        "id": "ef087383-ee5e-42c7-9a53-ab56c98420f9",
        "versionSpec": "*"
      },
      "inputs": {
        "testAssembly": "**\\*test*.dll;-:**\\obj\\**",
        "testFiltercriteria": "",
        "runSettingsFile": "",
        "codeCoverageEnabled": "true",
        "otherConsoleOptions": "",
        "vsTestVersion": "14.0",
        "pathtoCustomTestAdapters": ""
      }
    }
  ],
  "repository": {
    "id": "278d5cd2-584d-4b63-824a-2ba458937249",
    "type": "tfsgit",
    "name": "Fabrikam-Fiber-Git",
    "localPath": "$(sys.sourceFolder)/MyGitProject",
    "defaultBranch": "refs/heads/master",
    "url": "https://fabrikam.visualstudio.com/DefaultCollection/_git/Fabrikam-Fiber-Git",
    "clean": "false"
  },
  "options": [
    {
      "enabled": true,
      "definition": {
        "id": "7c555368-ca64-4199-add6-9ebaf0b0137d"
      },
      "inputs": {
        "parallel": "false",
        "multipliers": "[\"config\",\"platform\"]"
      }
    }
  ],
  "variables": {
    "forceClean": {
      "value": "false",
      "allowOverride": true
    },
    "config": {
      "value": "debug, release",
      "allowOverride": true
    },
    "platform": {
      "value": "any cpu",
      "allowOverride": true
    }
  },
  "triggers": [],
  "comment": "renamed"
}

As how to invoke Rest API in powershell, there are multiple samples in google, you could also take a look at this one:

$body = '
{ 
       ...
}
'
$bodyJson=$body | ConvertFrom-Json
Write-Output $bodyJson
$bodyString=$bodyJson | ConvertTo-Json -Depth 100
Write-Output $bodyString
$user="name"
$token="PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$Uri = "rest api url"
$buildresponse = Invoke-RestMethod -Method Post -UseDefaultCredentials -ContentType application/json -Uri $Uri -Body $bodyString -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
write-host ....

Comments

0

Finally I created / added an scheduled trigger to my build definition. When the build definition has not any trigger, the property (build object) or json array (build object convert to an array) doesn't exist. So, we've to add it. Here is the solution:

$triggerValue = @"
[
  {
    "schedules":[
        {
            "branchFilters":[
                "+$/FilterName"
            ],
            "timeZoneId":"W. Europe Standard Time",
            "startHours":$startHoursNB,
            "startMinutes":$startMinutesNB,
            "daysToBuild":"all"
        }
    ],
    "triggerType":"schedule"
  }
]
"@

$buildDef | add-member -Name "triggers" -value (Convertfrom-Json $triggerValue) -MemberType NoteProperty

Thanks also for help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.