Created
December 6, 2016 21:21
-
-
Save chrisbrownie/f20cb4508975fb7fb5da145d3d38024a to your computer and use it in GitHub Desktop.
PowerShell function to download files from a GitHub repository
This file contains hidden or 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 DownloadFilesFromRepo { | |
Param( | |
[string]$Owner, | |
[string]$Repository, | |
[string]$Path, | |
[string]$DestinationPath | |
) | |
$baseUri = "https://api.github.com/" | |
$args = "repos/$Owner/$Repository/contents/$Path" | |
$wr = Invoke-WebRequest -Uri $($baseuri+$args) | |
$objects = $wr.Content | ConvertFrom-Json | |
$files = $objects | where {$_.type -eq "file"} | Select -exp download_url | |
$directories = $objects | where {$_.type -eq "dir"} | |
$directories | ForEach-Object { | |
DownloadFilesFromRepo -Owner $Owner -Repository $Repository -Path $_.path -DestinationPath $($DestinationPath+$_.name) | |
} | |
if (-not (Test-Path $DestinationPath)) { | |
# Destination path does not exist, let's create it | |
try { | |
New-Item -Path $DestinationPath -ItemType Directory -ErrorAction Stop | |
} catch { | |
throw "Could not create path '$DestinationPath'!" | |
} | |
} | |
foreach ($file in $files) { | |
$fileDestination = Join-Path $DestinationPath (Split-Path $file -Leaf) | |
try { | |
Invoke-WebRequest -Uri $file -OutFile $fileDestination -ErrorAction Stop -Verbose | |
"Grabbed '$($file)' to '$fileDestination'" | |
} catch { | |
throw "Unable to download '$($file.path)'" | |
} | |
} | |
} |
If the repo is private...
$token = "<Create a Personal Access Token>"
$headers = @{Authorization = "token $($token)"}
Invoke-WebRequest -Headers $headers -Uri $uri
If the repo is private...
$token = "<Create a Personal Access Token>" $headers = @{Authorization = "token $($token)"} Invoke-WebRequest -Headers $headers -Uri $uri
Thank you @StanleyGoldman , So difficult to find this specific scenario cleanly presented.
I am new on GitHub. This article was very useful. Thank you very much.
Does this also work with fine grained access tokens? Trying this script out and changing bits here and there but whatever i do, i cant get it to work.
not bad
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I need help with this too.