Last active
March 14, 2025 10:17
-
-
Save hkboujrida/7788f71e6f0b1e05b8708ddc9fed20b1 to your computer and use it in GitHub Desktop.
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
param ( | |
[Parameter(Mandatory = $true)] | |
[string]$Organization, | |
[Parameter(Mandatory = $true)] | |
[string]$Project, | |
[Parameter(Mandatory = $true)] | |
[string]$ClientId, | |
[Parameter(Mandatory = $true)] | |
[string]$ClientSecret, | |
[Parameter(Mandatory = $true)] | |
[string]$TenantId, | |
[Parameter(Mandatory = $true)] | |
[string]$Scopes = "vso.build_execute vso.code_write vso.release_execute", # Default scopes | |
[Parameter(Mandatory = $true)] | |
[string]$DisplayName | |
) | |
# Get access token | |
$TokenUrl = "https://login.microsoftonline.com/$TenantId/oauth2/token" | |
$Resource = "499b84ac-1321-427f-aa17-267ca6975798" # Azure DevOps resource ID | |
$Body = @{ | |
grant_type = "client_credentials" | |
client_id = $ClientId | |
client_secret = $ClientSecret | |
resource = $Resource | |
} | |
try { | |
$TokenResponse = Invoke-RestMethod -Uri $TokenUrl -Method Post -Body $Body | |
$AccessToken = $TokenResponse.access_token | |
if (-not $AccessToken) { | |
Write-Error "Failed to get access token. Token response: $($TokenResponse | ConvertTo-Json)" | |
return | |
} | |
# Generate PAT | |
$PatUrl = "https://$Organization/_apis/tokens/pats?api-version=7.0" | |
$PatBody = @{ | |
displayName = $DisplayName | |
scope = $Scopes -join " " # Join scopes with spaces | |
validTo = $null | |
} | ConvertTo-Json | |
$Headers = @{ | |
Authorization = "Bearer $AccessToken" | |
"Content-Type" = "application/json" | |
} | |
$PatResponse = Invoke-RestMethod -Uri $PatUrl -Method Post -Headers $Headers -Body $PatBody | |
$Pat = $PatResponse.token | |
if (-not $Pat) { | |
Write-Error "Failed to generate PAT. PAT response: $($PatResponse | ConvertTo-Json)" | |
return | |
} | |
Write-Host "Generated PAT: $Pat" | |
} | |
catch { | |
Write-Error "Error: $($_.Exception.Message)" | |
if ($TokenResponse) { | |
Write-Error "Token error response: $($TokenResponse | ConvertTo-Json)" | |
} | |
if($PatResponse){ | |
Write-Error "PAT Error response: $($PatResponse | ConvertTo-Json)" | |
} | |
} | |
#.\generate_pat.ps1 -Organization "dev.azure.com/your-organization" -Project "YourProject" -ClientId "your-client-id" -ClientSecret "your-client-secret" -TenantId "your-tenant-id" -Scopes "vso.build_execute vso.code_write vso.release_execute" -DisplayName "Service Principal PAT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment