Issue
"I have a project on Azure DevOps with two repositories: repoTest1 and repoTest2. On repoTest2, on the main branch, I would like to create and apply this pull request policy with the following script:
$AzureDevOpsPAT = "2tkznxagtvfahaxxxxxxxxxxxxxxxxxxxx"
$OrganizationName = "myOrg"
$project = "myproj"
$branchName="main"
$repositoryIdD= "74d57bxxxxxxxxxxxxxxxxxxx"
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$url="https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/policy/configurations?repositoryId=$($repositoryId)&api-version=6.0"
$json = @{
isEnabled = $true
isBlocking = $true
settings = @{
scope = @("ref/heads/$($branchName)")
minimumApproverCount = 1
creatorVoteCounts = $false
}
type = @{
name = "myPolicyName"
}
}
$response = Invoke-RestMethod -Uri $url -Headers $AzureDevOpsAuthenicationHeader -Method POST -Body $JSON -ContentType application/json
it doesn't seem to work. The response keeps returning a value with two objects inside that seem to be my repositories. Another thing that I probably pass incorrectly is the repositoryId; I imagine there is a way to retrieve it dynamically.
Thanks for any help!
Solution
Here is the PowerShell script to get the repository ID via Repositories - Get Repository and create new policy for branch.
$AzureDevOpsPAT = "xxxxxxxxxxxxxxxxxxxxxxx"
$OrganizationName = "OrganizationName"
$projectName = "projectName"
$branchName="branchName"
$repositoryName= "repositoryName"
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
#Repositories - Get Repository
$url1="https://dev.azure.com/$($OrganizationName)/$($projectName)/_apis/git/repositories/$($repositoryName)?api-version=6.0"
$RepositoryInfo = Invoke-RestMethod -Uri $url1 -Method 'GET' -Headers $AzureDevOpsAuthenicationHeader
$repositoryID=$RepositoryInfo.id
echo "The repo $repositoryName's repositoryID we need is $repositoryID"
#Policy Configurations - post
$url2="https://dev.azure.com/$($OrganizationName)/$($projectName)/_apis/policy/configurations?api-version=6.0"
$json = @"
{
"type": {
"id": "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd"
},
"isDeleted": false,
"isBlocking": true,
"isEnabled": true,
"settings": {
"allowDownvotes": false,
"blockLastPusherVote": false,
"creatorVoteCounts": false,
"requireVoteOnLastIteration": false,
"resetOnSourcePush": false,
"resetRejectionsOnSourcePush": false,
"requireVoteOnEachIteration": false,
"minimumApproverCount": 1,
"scope": [
{
"repositoryId": "$repositoryID",
"refName": "refs/heads/$branchName",
"matchKind": "Exact"
}
]
}
}
"@
$response=""
$response = Invoke-RestMethod -Uri $url2 -Headers $AzureDevOpsAuthenicationHeader -Method POST -Body $JSON -ContentType application/json
$response | ConvertTo-Json
Answered By - Miao Tian-MSFT Answer Checked By - Mildred Charles (WPSolving Admin)