Search tools, AI agents, MCP servers
Submit a tool

Search iThub

Search tools, categories and collections. Type at least two characters.

Explore all tools
↑ ↓ to explore resultsEnter to open · Esc to close

Version Control & Code Hosting

Automate GitHub repo setup with PowerShell

Two original PowerShell scripts that install GitHub CLI and create or clone repositories, explained line by line with the full code to copy.

iThub Insights cover: automate GitHub repo setup with PowerShell
On this page
  1. What the installer script does
  2. What the repository script does
  3. How to save and run them
  4. FAQ

Setting up GitHub CLI on a new machine and then creating or cloning a repository is a short list of steps, but it is a list you end up repeating on every new laptop, every fresh VM, and every teammate's machine. Install the CLI for the right operating system, make sure it actually lands on PATH, sign in, then type out gh repo create or gh repo clone with the right flags. None of it is hard, all of it is easy to get slightly wrong, and it is exactly the kind of chore that is worth automating once and never thinking about again.

These two PowerShell scripts do that. The first one, Install-GitHubCli.ps1, installs GitHub CLI using whichever package manager fits the current operating system and then proves the install worked by actually running gh --version. The second, GitHub-Repository.ps1, wraps the two most common gh repo operations, creating a repository and cloning one, behind a pair of PowerShell parameter sets with validation on the inputs. Both scripts are defensive by design: they check for the tools they depend on before touching anything, they surface the real exit code when a command fails instead of swallowing it, and running the installer a second time on a machine that already has GitHub CLI does not reinstall anything, it just confirms the existing install and reports its version.

GitHub CLI itself, which both scripts are built around, is GitHub's own official command-line tool for working with GitHub repositories, issues, and pull requests without leaving the terminal.

What the installer script does

Install-GitHubCli.ps1 starts by checking whether gh is already on PATH. On Windows, if it is not found right away, the script also rebuilds the current session's PATH from the machine and user PATH values before checking again, because a winget install from an earlier session can leave gh installed without the current shell knowing about it yet. If gh turns up at that point, the script skips installation entirely and jumps straight to verification, which is what makes running it a second time safe: it reports the existing version instead of trying to install over it.

When gh genuinely is not found, the script picks an installer based on the operating system it detects:

  • On Windows, it runs winget install with the exact package ID GitHub.cli, then rebuilds PATH again so the newly installed gh is usable without opening a new terminal window, which is normally required after a winget install.
  • On macOS, it runs brew install gh.
  • On Linux, it walks through apt-get, dnf, and pacman in that order and uses the first one it finds on the system, running apt-get update first when that is the manager in use. It only prepends sudo when the current user is not already root, checked with id -u, so it will not try to call sudo on a system where it is not needed or not available.

If none of the three Linux package managers exist on the system, the script stops with an error pointing at GitHub's own Linux install documentation, since a distribution outside those three needs a different approach.

Once installation finishes (or was skipped because gh was already present), the script locates gh again and runs gh --version through its own checked-command helper, which throws if the exit code is not zero. That is the actual proof that the install works, not just that a package manager said it succeeded. On a fresh install it also times the whole thing with a stopwatch and prints how long it took. The one manual step it deliberately leaves to you, and prints a reminder for, is signing in: run gh auth login yourself afterward.

To run it:

./Install-GitHubCli.ps1

Here is the complete script, unmodified:

#Requires -Version 5.1
<#
.SYNOPSIS
Installs GitHub CLI and verifies that gh runs.

.DESCRIPTION
Uses WinGet on Windows, Homebrew on macOS, and apt-get, DNF, or
pacman on Linux. Linux uses your configured package repositories.
Run the installer again to check an existing installation.

.EXAMPLE
./Install-GitHubCli.ps1

.LINK
https://github.com/cli/cli#installation
#>
[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false

function Find-Application {
    param([string]$Name)

    Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue |
        Select-Object -First 1
}

function Invoke-CheckedCommand {
    param(
        [string]$Name,
        [string[]]$CommandArguments
    )

    $application = Find-Application $Name
    if (-not $application) {
        throw "Required command '$Name' was not found on PATH."
    }

    & $application.Path @CommandArguments
    if ($LASTEXITCODE -ne 0) {
        throw "$Name $($CommandArguments -join ' ') exited with code $LASTEXITCODE."
    }
}

function Update-WindowsPath {
    $paths = @(
        $env:Path
        [Environment]::GetEnvironmentVariable('Path', 'Machine')
        [Environment]::GetEnvironmentVariable('Path', 'User')
    )
    $env:Path = (($paths -split ';') | Where-Object { $_ } | Select-Object -Unique) -join ';'
}

function Install-LinuxGitHubCli {
    $installArguments = [ordered]@{
        'apt-get' = @('install', 'gh')
        'dnf'     = @('install', 'gh')
        'pacman'  = @('-S', '--needed', 'github-cli')
    }

    foreach ($managerName in $installArguments.Keys) {
        $manager = Find-Application $managerName
        if (-not $manager) {
            continue
        }

        $command = $manager.Path
        $prefix = @()
        $userId = Invoke-CheckedCommand 'id' @('-u')
        if ($userId -ne '0') {
            $command = 'sudo'
            $prefix = @('--', $manager.Path)
        }

        if ($managerName -eq 'apt-get') {
            Invoke-CheckedCommand $command ($prefix + 'update')
        }

        Invoke-CheckedCommand $command ($prefix + $installArguments[$managerName])
        return
    }

    throw 'A supported Linux package manager is required. See https://github.com/cli/cli/blob/trunk/docs/install_linux.md for other installation methods.'
}

try {
    $onWindows = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
    $githubCli = Find-Application 'gh'
    if ($onWindows -and -not $githubCli) {
        Update-WindowsPath
        $githubCli = Find-Application 'gh'
    }

    $stopwatch = $null
    if (-not $githubCli) {
        Write-Host 'Installing GitHub CLI...'
        $stopwatch = [Diagnostics.Stopwatch]::StartNew()

        if ($onWindows) {
            Invoke-CheckedCommand 'winget' @(
                'install', '--id', 'GitHub.cli', '--exact', '--source', 'winget', '--no-upgrade'
            )
            Update-WindowsPath
        }
        elseif ($IsMacOS) {
            Invoke-CheckedCommand 'brew' @('install', 'gh')
        }
        elseif ($IsLinux) {
            Install-LinuxGitHubCli
        }
        else {
            throw 'This installer supports Windows, macOS, and Linux.'
        }

        $githubCli = Find-Application 'gh'
        if (-not $githubCli) {
            throw 'Installation finished, but gh is missing from PATH. Open a new terminal and run gh --version.'
        }
    }

    Invoke-CheckedCommand $githubCli.Path @('--version')
    if ($stopwatch) {
        $stopwatch.Stop()
        Write-Host ('GitHub CLI is ready after {0:F1} seconds.' -f $stopwatch.Elapsed.TotalSeconds)
    }
    else {
        Write-Host 'GitHub CLI is already available.'
    }

    Write-Host 'To sign in, run gh auth login.'
    exit 0
}
catch {
    Write-Error -Message "GitHub CLI setup failed. $($_.Exception.Message)" -ErrorAction Continue
    exit 1
}

What the repository script does

GitHub-Repository.ps1 covers the two things you actually do with gh repo day to day: creating a new repository and cloning an existing one. It uses PowerShell parameter sets to keep those two modes apart, so -Create and -Clone cannot both be passed in the same call. PowerShell itself rejects the call before the script body even runs if you try to mix them.

Before doing anything, the script checks that gh is on PATH at all and throws immediately if it is not, pointing you at installing it and running gh auth login. When you are cloning, or creating with -CloneAfterCreate, it also checks for git and throws if that is missing, since gh repo clone and the --clone flag both need it under the hood.

Creating a repository takes -Create with an OWNER/REPO string, validated against a regular expression so a typo gets caught locally instead of as a confusing error from GitHub's API. A created repository is private by default and always gets a README added (--add-readme); pass -Public if you want it public instead. Add -CloneAfterCreate to clone it to your current directory right after creation, in the same gh repo create call via its own --clone flag.

Cloning a repository takes -Clone, which accepts either an OWNER/REPO string or a full https://github.com/... URL, again checked with a validation pattern before anything runs. The optional -Destination parameter sets where the clone lands locally; the script resolves whatever path you give it, relative or absolute, against your current location before handing it to gh.

If the underlying gh call fails, the script throws using gh's own exit code in the message rather than inventing its own error text. There is one extra detail specifically for -CloneAfterCreate: because that flag runs repository creation and cloning as a single gh repo create ... --clone call, a failure partway through can mean the repository was actually created on GitHub even though the clone step did not finish. The error message for that case tells you to retry just the clone with -Clone against the same name you passed to -Create, rather than trying to create the repository again.

A few example commands, adapted from the script's own help text:

./GitHub-Repository.ps1 -Create 'your-account/my-project'

Creates a new private repository named my-project under your-account, with a README, and leaves it on GitHub without cloning it locally.

./GitHub-Repository.ps1 -Create 'your-account/my-project' -Public -CloneAfterCreate

Creates the same repository as public instead of private, and clones it into the current directory right after creation finishes.

./GitHub-Repository.ps1 -Clone 'https://github.com/your-account/my-project' -Destination './my-copy'

Clones an existing repository by its full URL into a local folder named my-copy, rather than a folder named after the repository itself.

Here is the complete script, unmodified:

#Requires -Version 5.1
<#
.SYNOPSIS
Creates or clones a GitHub repository.

.DESCRIPTION
Install GitHub CLI and sign in with gh auth login. Cloning also requires Git.
Use OWNER/REPO when creating a repository. Cloning also accepts a GitHub.com
HTTPS URL. A new repository is private by default and includes a README.

.PARAMETER Public
Creates a public repository.

.PARAMETER CloneAfterCreate
Clones the new repository into the current directory.

.PARAMETER Destination
Sets the local directory for an existing repository clone.

.EXAMPLE
./GitHub-Repository.ps1 -Create 'your-account/my-project'

.EXAMPLE
./GitHub-Repository.ps1 -Create 'your-account/my-project' -Public -CloneAfterCreate

.EXAMPLE
./GitHub-Repository.ps1 -Clone 'https://github.com/your-account/my-project' -Destination './my-copy'
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory, ParameterSetName = 'Create')]
    [ValidatePattern('\A[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_.-]+\z')]
    [string]$Create,

    [Parameter(Mandatory, ParameterSetName = 'Clone')]
    [ValidatePattern('\A(?:https://github\.com/)?[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_.-]+\z')]
    [string]$Clone,

    [Parameter(ParameterSetName = 'Create')]
    [switch]$Public,

    [Parameter(ParameterSetName = 'Create')]
    [switch]$CloneAfterCreate,

    [Parameter(ParameterSetName = 'Clone')]
    [ValidateNotNullOrEmpty()]
    [string]$Destination
)

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false

$githubCli = Get-Command -Name gh -CommandType Application -ErrorAction SilentlyContinue |
    Select-Object -First 1
if (-not $githubCli) {
    throw 'Install GitHub CLI (gh) and sign in with gh auth login.'
}

$isCreating = $PSCmdlet.ParameterSetName -eq 'Create'
if ((-not $isCreating -or $CloneAfterCreate) -and
    -not (Get-Command -Name git -CommandType Application -ErrorAction SilentlyContinue)) {
    throw 'Install Git before cloning a repository.'
}

if ($isCreating) {
    $visibility = '--private'
    if ($Public) {
        $visibility = '--public'
    }

    $githubArguments = @('repo', 'create', $Create, $visibility, '--add-readme')
    if ($CloneAfterCreate) {
        $githubArguments += '--clone'
    }
}
else {
    $githubArguments = @('repo', 'clone', $Clone)
    if ($Destination) {
        $localPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
        $githubArguments += $localPath
    }
}

& $githubCli.Path @githubArguments
if ($LASTEXITCODE -ne 0) {
    $message = "GitHub CLI exited with code $LASTEXITCODE."
    if ($CloneAfterCreate) {
        $message += " If the repository was created, retry the clone with -Clone '$Create'."
    }

    throw $message
}

How to save and run them

Save each script under its own name, Install-GitHubCli.ps1 and GitHub-Repository.ps1, and run them from an actual PowerShell prompt, not from cmd.exe, using the leading ./ so PowerShell knows you mean the local file and not a command of the same name somewhere on PATH.

The #Requires -Version 5.1 line at the top of both scripts means they work on Windows PowerShell 5.1, the version that ships built into Windows, and on PowerShell 7 and later, including on macOS and Linux where PowerShell 7 is the version you would be running anyway. You do not need to install anything extra just to run the scripts themselves.

One common gotcha on Windows: if you have never run a local script before, PowerShell's execution policy may block it with a message about running scripts being disabled on the system. A common way around that for a single session, mentioned here purely as a fact about the environment rather than as a recommendation either way, is Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass, which only affects the current PowerShell process and reverts once it closes.

FAQ

Does this work on macOS and Linux, or only Windows? Both scripts detect the operating system at runtime. The installer uses Homebrew on macOS and tries apt-get, dnf, and pacman in order on Linux, and the repository script's only platform-specific step is the Windows-only PATH rebuild inside the installer, so the repository script itself runs the same way on any OS that has gh and, when needed, git on PATH.

Do I need administrator or root rights to run the installer? Not necessarily. On Windows, a per-user winget install does not require elevation. On Linux, the script only adds sudo in front of the package manager command when the current user is not already root, checked with id -u, so it will not call sudo unnecessarily and will not work around a system where sudo itself is unavailable and you are not root.

What happens if GitHub CLI is already installed when I run the installer? The script finds it on PATH, skips the install step entirely, and goes straight to running gh --version to confirm it and print the version, rather than attempting to reinstall or upgrade it.

Can I create a public repository without also cloning it? Yes. -Public and -CloneAfterCreate are independent switches on the -Create parameter set. Passing -Public on its own creates a public repository with a README and leaves it on GitHub; cloning only happens if you also pass -CloneAfterCreate.

What if -CloneAfterCreate fails partway through? Because creation and cloning happen in one gh repo create ... --clone call, a failure there can mean the repository already exists on GitHub even though nothing was cloned locally yet. The script's own error message tells you to retry with -Clone against the same OWNER/REPO name instead of running -Create again.

Does cloning accept a plain OWNER/REPO name, or only a full URL? Both. The -Clone parameter's validation pattern accepts either an OWNER/REPO string or a full https://github.com/... URL.

Is PowerShell 7 required to run these? No. Both scripts only declare #Requires -Version 5.1, so the PowerShell that already ships with Windows is enough. PowerShell 7 works too, on Windows or elsewhere, since it satisfies that same minimum version.

These are original utility scripts written for this purpose, included here in full as the site's own practical tool content.

Frequently asked questions

Does this work on macOS and Linux, or only Windows?

Both scripts detect the operating system at runtime. The installer uses Homebrew on macOS and tries apt-get, dnf, and pacman in order on Linux, and the repository script's only platform-specific step is the Windows-only PATH rebuild inside the installer, so the repository script itself runs the same way on any OS that has gh and, when needed, git on PATH.

Do I need administrator or root rights to run the installer?

Not necessarily. A per-user winget install on Windows does not require elevation, and on Linux the script only adds sudo in front of the package manager command when the current user is not already root.

What happens if GitHub CLI is already installed when I run the installer?

It finds gh on PATH, skips the install step, and runs gh --version to confirm the existing install and print its version, instead of attempting to reinstall or upgrade anything.

Can I create a public repository without also cloning it?

Yes, Public and CloneAfterCreate are independent switches on the Create parameter set, so a public repository with a README can be created on GitHub and left there, with cloning happening only when CloneAfterCreate is also passed.

What if CloneAfterCreate fails partway through?

Since creation and cloning run as one gh repo create call with the clone flag, a failure there can mean the repository already exists on GitHub even though the clone did not finish, and the script's error message points at retrying just the clone against that same owner and repo name.

Does cloning accept a plain OWNER/REPO name, or only a full URL?

Either one. The Clone parameter's validation pattern matches an OWNER/REPO string or a full github.com HTTPS URL.

Is PowerShell 7 required to run these?

No, both scripts only declare a minimum of version 5.1, which the PowerShell built into Windows already satisfies, and PowerShell 7 and later on any platform satisfies it as well.

Tools in this article

  1. GitHubGit hosting with pull requests, Actions CI/CD, Copilot, Codespaces and a self-hosted Enterprise ServerVersion Control & Code Hosting73 views
Share this article

Facts link to their official sources. Product details can change after publication: report an error or read the editorial methodology.

Emanuel DE ALMEIDA

Written by

Emanuel DE ALMEIDA

Entrepreneur · IT consultant · Software creator

Geneva-based entrepreneur, IT consultant and creator of SuniPDF and SuniCapture. Emanuel shares practical IT, cybersecurity and software insights on iThub.

Keep reading

More guides and analysis from the iThub editors.

All insights
Support for password authentication was removed: how to fix GitWhy GitHub rejects your Git password since August 13, 2021, and how to fix it with a personal access token, SSH key, Git Credential Manager or the gh CLI.The complete guide to deploying on RenderHow Render's service types, deploy methods, free tier, and preview environments really work, verified against Render's own current docs and pricing.How AI slide generators create real, editable PowerPoint filesAI slide generators usually output flattened images or generic templates. See how SVG-to-DrawingML conversion creates real, editable PowerPoint files.