Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@EbenZhang
Last active November 21, 2022 09:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EbenZhang/f89113ccc04f90af5e41aa739c5e086a to your computer and use it in GitHub Desktop.
Save EbenZhang/f89113ccc04f90af5e41aa739c5e086a to your computer and use it in GitHub Desktop.
Powershell to call GitHub Api using personal token
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