-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSet-Collab-GITHUB-Repository-Remotely-Example.ps1
78 lines (56 loc) · 2.1 KB
/
Set-Collab-GITHUB-Repository-Remotely-Example.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Environment variables for GitHub username and PAT
$githubUser = [System.Environment]::GetEnvironmentVariable('GITHUB_USERNAME')
#
$githubToken = [System.Environment]::GetEnvironmentVariable('GITHUB_PERSONAL_ACCESS_TOKEN')
# Using Environment Variable
#$newCollaboratorUsername = [System.Environment]::GetEnvironmentVariable('NEW_COLLABORATOR_USERNAME')
# Hard Coding User Name
$newCollaboratorUsername = "(GITHUB User Name)"
# Base URL for GitHub API
$apiUrlBase = 'https://api.github.com'
# Headers for authentication
$headers = @{
Authorization = "token $githubToken"
Accept = 'application/vnd.github.v3+json'
}
function List-Repositories {
param (
[string]$user
)
# List all repositories for the user
$reposUrl = "$apiUrlBase/users/$user/repos"
try {
$response = Invoke-RestMethod -Uri $reposUrl -Method Get -Headers $headers
return $response
}
catch {
throw $_.Exception.Message
}
}
function Add-CollaboratorToRepo {
param (
[string]$repoName,
[string]$collaboratorUsername
)
# Add a collaborator to a specific repository
$collaboratorsUrl = "$apiUrlBase/repos/$githubUser/$repoName/collaborators/$collaboratorUsername"
try {
# Use PUT method to add a collaborator, ignore the response body with Out-Null
Invoke-RestMethod -Uri $collaboratorsUrl -Method Put -Headers $headers | Out-Null
Write-Host "Successfully added $collaboratorUsername to $repoName"
return $true;
} catch {
Write-Host "Failed to add $collaboratorUsername to $repoName. Status code: $_.Exception.Response.StatusCode.Value__"
return $false;
}
}
try {
# List all repositories and add new collaborator to each one.
List-Repositories -user $githubUser | ForEach-Object {
Add-CollaboratorToRepo -repoName $_.name -collaboratorUsername $newCollaboratorUsername
}
Write-Host "All done!"
} catch {
Write-Host "An error occurred: $_"
}
#end of script