Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active August 16, 2023 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/2ca3086fc028c40e30d15f883e601ec2 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/2ca3086fc028c40e30d15f883e601ec2 to your computer and use it in GitHub Desktop.
Azure DevOps - Create A New Branch In Git Repository
$devopsApiVersion = "7.0"
$newBranch = "sprint/userStoryNumber";
$baseBranch = "master";
$organization = "contoso";
$project = "contoso";
$repository = "contosowebapp";
## -----------------------------------------------------------------
## Create Branch
## -----------------------------------------------------------------
createNewBranch($organization, $project, $repository, $baseBranch, $newBranch, $headers, $devopsApiVersion);
## -----------------------------------------------------------------
## Generate Auth Header
## -----------------------------------------------------------------
$pat = "<<your-personal-access-token>>"
$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$pat"))
$headers = @{ Authorization = "Basic $base64AuthInfo" }
## -----------------------------------------------------------------
## Function - To Generate New Branch From Given Base Branch
## -----------------------------------------------------------------
function createNewBranch($organization, $project, $repository, $baseBranch, $newBranch, $headers, $version)
{
## -----------------------------------------------------------------
## Get ID of the base branch
## -----------------------------------------------------------------
$getBaseBranchUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?filter=heads/$baseBranch&api-version=$version"
$baseBranchResponse = Invoke-RestMethod -Uri $getBaseBranchUrl -ContentType "application/json" -headers $headers -Method GET
## -----------------------------------------------------------------
## Create a new branch
## -----------------------------------------------------------------
$createNewBranchUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?api-version=$version"
$body = ConvertTo-Json @(
@{
name = "refs/heads/$newBranch"
newObjectId = $baseBranchResponse.value.objectId
oldObjectId = "0000000000000000000000000000000000000000"
})
$response = Invoke-RestMethod -Uri $createNewBranchUrl -ContentType "application/json" -Body $body -headers $headers -Method POST
Write-Host $response.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment