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).

Scroll to Top