Last active
November 21, 2022 09:12
-
-
Save EbenZhang/f89113ccc04f90af5e41aa739c5e086a to your computer and use it in GitHub Desktop.
Powershell to call GitHub Api using personal token
This file contains 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
function CreateGitHubRequestHeaders([string]$username, [string]$token){ | |
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 | |
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$token))) | |
$headers = @{Authorization="Basic $base64AuthInfo"} | |
return $headers | |
} | |
function GetRestfulErrorResponse($exception) { | |
$ret = "" | |
if($exception.Exception -and $exception.Exception.Response){ | |
$result = $exception.Exception.Response.GetResponseStream() | |
$reader = New-Object System.IO.StreamReader($result) | |
$reader.BaseStream.Position = 0 | |
$reader.DiscardBufferedData() | |
$ret = $reader.ReadToEnd() | |
$reader.Close() | |
} | |
if($ret -eq $null -or $ret.Trim() -eq ""){ | |
$ret = $exception.ToString() | |
} | |
return $ret | |
} | |
$headers = CreateGitHubRequestHeaders -username <your user name> -token <your token> | |
$url = 'https://api.github.com//repos/<YourAccount>/<YourRepo>/<the endpoint>' | |
$body = @{ | |
# whatever required by the endpoint | |
# head = "$head" | |
# base = "$base" | |
} | ConvertTo-Json | |
Try{ | |
Invoke-RestMethod -Method <Post|Get|Put> ` | |
-Uri $url ` | |
-Headers $headers ` | |
-Body $body # for POST and PUT | |
} Catch { | |
$resp = (GetRestfulErrorResponse $_) | |
Write-Error $resp | |
throw | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment