Skip to content

Instantly share code, notes, and snippets.

@chrisbrownie
Created December 6, 2016 21:21
Show Gist options
  • Save chrisbrownie/f20cb4508975fb7fb5da145d3d38024a to your computer and use it in GitHub Desktop.
Save chrisbrownie/f20cb4508975fb7fb5da145d3d38024a to your computer and use it in GitHub Desktop.
PowerShell function to download files from a GitHub repository
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)'"
}
}
}
@marchro
Copy link

marchro commented Mar 16, 2021

I am new on GitHub. This article was very useful. Thank you very much.

@thisislukasbenz
Copy link

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.

@kyaw0089
Copy link

not bad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment