Last active
August 16, 2023 10:36
-
-
Save manoj-choudhari-git/2ca3086fc028c40e30d15f883e601ec2 to your computer and use it in GitHub Desktop.
Azure DevOps - Create A New Branch In Git Repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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