Create a GitHub Repo with PowerShell

Dave Lloyd
ObjectSharp (a Centrilogic Company)
2 min readJul 8, 2022

The GitHub Rest API is very good and very well documented.

However the examples are all for cURL, JavaScript and GitHub CLI. I know PowerShell, I am very comfortable with it, and it’s very powerful. So 90% of the scripts I write are in PowerShell. Therefore…

Here is an example of creating a new GitHub Repo using PowerShell. There are many options available (see GitHub Documentation) however for this example lets keep it simple. We’ll create a new Repo in a GitHub Org.

You will need a Personal Access Token (PAT) to execute the API call. Follow these instructions to create yourself a PAT.

For my example I’ll create a Powershell script called createGHRepo.ps1 with:

  • One parameter: The name of the repo we want to create.
  • A variables with the GitHub organization name. Could also be a parameter obviously.
  • A variable with the Personal Access Token we will get from an environment variable, converted to base64.
param (
[Parameter(Mandatory=$true)] $repoName
)
$orgName = "myOrg"
$pat = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($env:GH_PAT)"))

For the body of the Rest API Call. The only mandatory parameter is name. There are many more, they are either not required or will default to some value, see Documentation for the other options.

$body = @{name="$repoName"} 

Now lets set up the call to Invoke-RestMethod.

$params = @{
'Uri' = ('https://api.github.com/orgs/{0}/repos' -f $orgName)
'Headers' = @{'Authorization' = 'Basic ' + $pat}
'Method' = 'Post'
'ContentType' = 'application/json'
'Body' = ($body | ConvertTo-Json)}
Invoke-RestMethod @params

Here is the whole script:

param ([Parameter(Mandatory=$true)] $repoName)
$orgName = "myOrg"
$pat = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($env:GH_PAT)"))
$body = @{name="$repoName"}
$params = @{
'Uri' = ('https://api.github.com/orgs/{0}/repos' -f $orgName)
'Headers' = @{'Authorization' = 'Basic ' + $pat}
'Method' = 'Post'
'ContentType' = 'application/json'
'Body' = ($body | ConvertTo-Json)}
Invoke-RestMethod @params

Now just make the call to create new repos.

./createGHRepo.ps1 -repoName "myNewRepo"

--

--

Dave Lloyd
ObjectSharp (a Centrilogic Company)

I have been writing software and teaching/coaching developers for 40 years. I love sharing knowledge and experience.