Creating a TFS branch from PowerShell

The TFS API is really powerful and sometimes it’s just not very convenient to write a .NET app to consume it.  You can get just as much done with PowerShell and easily deploy and run the script on your servers.  I needed to create a TFS branch, but I could not use Team Explorer to do so, so I came up with this script (simplified version). 

param(
 
)
begin
{
 # load the required dll's
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
    
}
 
process
{
 $server = New-Object Microsoft.TeamFoundation.Client.TeamFoundationServer("http://tfsserver:8080/tfs/DefaultCollection")
 
 $vcServer = $server.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]); 

 $changesetId = $vcServer.CreateBranch('$/Demo/Code/Main', '$/Demo/Code/Dev/Branch', [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest, $null, "New branch from script", $null, $null, $null)

 "Branch created with ChangesetID: $changesetId"
 
}

This uses the VersionControlServer.CreateBranch() method, which runs server-side, which means that there’s no need to create a workspace or commit after the branch is created.  There is a simpler overload, but that one doesn’t let you specify comments, so I chose this one.  This creates a 2010-style branch (allows visualization).

About esteban

Esteban is the Founder and Chief Technologist at Nebbia Technology, an ALM consulting and Azure-powered technology company. He is a software developer with a passion for ALM, TFS, Azure, and software development best practices. Esteban is a Microsoft Visual Studio ALM MVP and ALM Ranger, Pluralsight author, and the president of ONETUG (Orlando .NET User Group).

3 thoughts on “Who needs a version control system?

  1. Julio

    Hi Esteban, really a very interesting and post, I think that use version control is a must and the points that you exposes are very clearly, I only want add that version control is a basic Step to begin with any software methodology like Scrum, and if you use tfs you have a really complete tool to help you in all the proccess to build software.

    Regards

  2. Ganesh kulpe

    Hi,

    I want to marge two branch with change set only from shell scripting. If you have any idea or script please provide me .

    Thanks
    Ganesh

  3. Neil W

    I use TFS 2015 cu3 and was attempting to create a code branch programmatically using the RESTAPI, but surprisingly and frustratingly, it’s not supported from what I could see. I came across your powershell script and it works beautifully.
    Can you believe your script is still being used 6 years later?
    Thanks.


Leave a Reply

Your email address will not be published. Required fields are marked *

Are you human? *