public/build/Add-PSTSBuildDefinitionTrigger.ps1

function Add-PSTSBuildDefinitionTrigger
{
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][object] $buildDefinition,
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string] $environment,
        [Parameter(ValueFromPipelineByPropertyName = $true)][string] $targetBuildName=$null,
        [Parameter(ValueFromPipelineByPropertyName = $true)][string] $targetBuildBranch=$null,
        [Parameter(ValueFromPipelineByPropertyName = $true)][string] $targetBuildproject= $null
    )

    process {

        [BuildDefinitionTrigger]$trigger = [BuildDefinitionTrigger]::new()
        $trigger.branchFilters +="+$($environment)"
        $trigger.batchChanges = $false
        $trigger.maxConcurrentBuildsPerBranch = 1
        $trigger.triggerType = "continuousIntegration"
        $buildDefinition.triggers+=$trigger

        if ( [string]::IsNullOrEmpty($targetBuildName) -eq $false ) {
            [BuildDefinitionTriggerDefinition]$definitionTrigger = [BuildDefinitionTriggerDefinition]::new()
            [BuildDefinition]$targetBuild = $(Get-PSTSBuildDefinition -project $targetBuildproject) | Where-Object { $_.name -eq $targetBuildName}



            $definitionTrigger.id = $targetBuild.Id
            $definitionTrigger.url = $targetBuild.url
            $definitionTrigger.Path = $targetBuild.Path
            $definitionTrigger.queueStatus = $targetBuild.queueStatus

            [Project]$project = $(Get-PSTSProject) | Where-Object { $_.name -eq $targetBuildproject }

            $objProject = New-Object -TypeName PSObject
            $objProject | Add-Member -MemberType NoteProperty -Name "id" -Value $project.id
            $objProject | Add-Member -MemberType NoteProperty -Name "name" -Value $project.name
            $objProject | Add-Member -MemberType NoteProperty -Name "url" -Value $project.url
            $objProject | Add-Member -MemberType NoteProperty -Name "state" -Value $project.state
            $objProject | Add-Member -MemberType NoteProperty -Name "revision" -Value $project.revision
            $objProject | Add-Member -MemberType NoteProperty -Name "visibility" -Value $project.visibility
            $objProject | Add-Member -MemberType NoteProperty -Name "lastUpdateTime" -Value $project.lastUpdateTime
            $definitionTrigger.project = $objProject
            


            [BuildDefinitionTriggerCompletion]$completionTrigger = [BuildDefinitionTriggerCompletion]::new()
            $completionTrigger.definition=$definitionTrigger
            $completionTrigger.requiresSuccessfulBuild = $true
            $completionTrigger.branchFilters+="+refs/heads/$($targetBuildBranch)"
            $completionTrigger.triggerType = "buildCompletion"
            $buildDefinition.triggers+=$completionTrigger
        }

        return $buildDefinition
    }
}