2

I use this power shell script to download files from Git Hub repository

$url = "https://gist.github.com/ . . ./test.jpg"
$output = "C:\Users\admin\Desktop\test.jpg"
$start_time = Get-Date

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)
#OR
(New-Object System.Net.WebClient).DownloadFile($url, $output)

Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)" 

It works well for one file. How can I download the full repository using PowerShell? I cannot use git pull.

EDIT Here is what I tried on a real repository.

Repository: https://github.com/githubtraining/hellogitworld/archive/master.zip

Here is a test code, but it doesn't download the repository completely

$url = "https://github.com/githubtraining/hellogitworld/archive/master.zip"
$output = "C:\Users\mycompi\Desktop\test\master.zip"
$start_time = Get-Date

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)

Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
john
  • 647
  • 5
  • 23
  • 53

1 Answers1

5

You can download a zipped copy of a branch at it's current HEAD from the following URL:

https://github.com/[owner]/[repository]/archive/[branch].zip

So to donwload the current master branch of the PowerShell repository on GitHub for example, you'd do:

$url = "https://github.com/PowerShell/PowerShell/archive/master.zip"
$output = "C:\Users\admin\Desktop\master.zip"
$start_time = Get-Date

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)

Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)" 

You could easily turn this into a reusable function:

function Save-GitHubRepository
{
    param(
        [Parameter(Mandatory)]
        [string]$Owner,

        [Parameter(Mandatory)]
        [string]$Project,

        [Parameter()]
        [string]$Branch = 'master'
    )

    $url = "https://github.com/$Owner/$Project/archive/$Branch.zip"
    $output = Join-Path $HOME "Desktop\${Project}-${Branch}_($(Get-Date -Format yyyyMMddHHmm)).zip"
    $start_time = Get-Date

    $wc = New-Object System.Net.WebClient
    $wc.DownloadFile($url, $output)

    Write-Host "Time taken: $((Get-Date).Subtract($start_time).TotalSeconds) second(s)" 
}

Then use it like:

PS C:\> Save-GitHubRepository PowerShell PowerShell
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    i tried this code on a real repository `https://github.com/githubtraining/hellogitworld/archive/master.zip` but it seems that the downloaded zip is invalid. Could you please take a look at my answer below? – john Feb 02 '18 at 03:35
  • I have the same problem as mentioned above. In my case, I am trying to download the whole repo as zip file... – user007 Apr 16 '21 at 20:41