Search code examples
powershelltfsbranching-and-mergingtfs-2015

How to get list of branches under TFS project programatically?


Need to get list of branches under a Team project collection or Team project, which is needed to written in some txt or csv file. I am using TFS 2015.

Is there is some scripts available? Preferably Powershell script

Thanks in Advance, Dinesh.


Solution

  • Both REST API and Client API can achieve what you need. You can also use them in the Powershell script.

    Using Rest API-Get a branch

     GET https://{instance}/DefaultCollection/_apis/tfvc/branches/{path}?api-version={version}[&includeChildren={bool}&includeParent={bool}&includeDeleted={bool}]
    

    Using Client API

    Using Powershell with C#

    # Define parameters 
    $tfsCollectionUrl = New-Object System.URI("http://ditfs.cloudapp.net:8080/tfs/disample");
    
    # Load Client Assembly 
    [Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”); 
    [Reflection.Assembly]::Load(“Microsoft.TeamFoundation.VersionControl.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”); 
    [Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”); 
    [Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Lab.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”); 
    [Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Lab.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”);  
    
    # Connect to tfs 
    $tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsCollectionUrl); 
    $projectService = $tfsCollection.GetService([Microsoft.TeamFoundation.Server.ICommonStructureService]);
    $versionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]);
    
    # Query all the projects and branches
    $projects = $projectService.ListAllProjects();
    $objallbranch = $versionControl.QueryRootBranchObjects("full")
    
    foreach ($project in $projects) 
    { 
      Write-Host Finding environments for project $project.Name
       foreach ($branchObject in $objallbranch)
                   {
                       if ($branchObject.Properties.RootItem.Item.ToUpper().Contains($project.Name.ToUpper()))
                       {
                           write-host $branchObject
                       }
                       }
    
    }
    

    Source code from GitHub