To script the Repository and branch security, you can use the tfssecurity.exe
or the new permissions REST API or the Azure CLI. All details in the following blog post:
For specific branches, add /refs^heads^master/
at the end of the Token.
Excerpt
If you've dug into the security innards of Azure DevOps in the past, you'll have found out that certain permissions are granted to persons or groups and are linked to a token. This token is usually built up out of a root object and a bunch of GUIDs. For example, this is the token for a specific Git Repository:
repoV2/daec401a-49b6-4758-adb5-3f65fd3264e3/f59f38e0-e8c4-45d5-8dee-0d20e7ada1b7
^ ^ ^
| | |
| | -- The Git Repository
| -- The Team Project Guid
|
-- The root object (Repositories)
Simplest way I know of to find these details, is to capture the web request made when a permission is changed:

You can use the Web Developer tools in your favorite browser to find the token you need.
Once you understand this, it's easy to find the token for the "All Repositories in a Team Project" token. Just take off the Git Repository GUID at the end:
repoV2/daec401a-49b6-4758-adb5-3f65fd3264e3b7/
^ ^
| |
| -- The Team Project Guid
|
-- The root object (Repositories)
And, using the same reasoning, to get to the token for "All repositories in the Project Collection/Organization" token. Just take off the Team Project GUID at the end:
repoV2/
^
|
-- The root object (Repositories)
And now that we have this token, we can use tfssecurity to set Organization level git permissions:
tfssecurity /a+ "Git Repositories" repoV2/ "PullRequestBypassPolicy" adm: ALLOW /collection:https://dev.azure.com/org
^ ^ ^ ^ ^ ^
| | | | | -- Allow or Deny the permission
| | | | -- The Group (in this case "Project Collection Administrators")
| | | -- The Permission we want to set
| | -- The Token we found above
| -- The Secuity Namespace
-- Add (a+) or Remove (a-) this permission
And, as you can see below, this trick actually works :).

You can use the same technique to secure branches. The token of a branch uses the token of the Repository as a basis and adds the branch to that. Because a /
is a token separator, a branch reference is escaped by replacing /
with ^
. Thus refs/heads/master
becomes: refs^heads^master
:
repoV2/daec401a-49b6-4758-adb5-3f65fd3264e3/f59f38e0-e8c4-45d5-8dee-0d20e7ada1b7/refs^heads^master/
^ ^ ^ ^
| | | |
| | | -- The branch
| | -- The Git Repository
| -- The Team Project Guid
|
-- The root object (Repositories)