Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Created April 3, 2023 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/c28dd17f582100fcf4a9ba18aa002c64 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/c28dd17f582100fcf4a9ba18aa002c64 to your computer and use it in GitHub Desktop.
Powershell function to retrieve a file from a Github repository
Set-StrictMode -Vesion Latest
function Invoke-GithubFileRequest {
<# .SYNOPSIS
Retrieves a file from a Github repository. #>
[Alias('gh_curl')]
Param(
# URL of file to download
[Parameter(Mandatory)]
[Uri]$URL,
# Output file path
[IO.FileInfo]$FilePath = $URL.Segments[-1]
)
function _validate {
Param([Uri]$link)
switch ($link.Host) {
'github.com' {
if ($link.Segments.Count -lt 6 -or $link.Segments[3] -ne 'blob/') { break }
return [Uri]('https://api.github.com/repos/{1}/{2}/contents/{5}?ref={4}' -f
$link.LocalPath.Split('/', 6))
}
'raw.githubusercontent.com' {
if ($link.Segments.Count -lt 5) { break }
return [Uri]('https://api.github.com/repos/{1}/{2}/contents/{4}?ref={3}' -f
$link.LocalPath.Split('/', 5))
}
'api.github.com' {
if ($link.LocalPath -notmatch 'git/blobs|contents') { break }
return $link
}
}
Write-Output 'The provided URL is not a valid Github file URL:' $link.OriginalString
break 2
}
[IO.File]::WriteAllBytes($FilePath, [Convert]::FromBase64String(
(Invoke-RestMethod -Uri (_validate $URL)).Content))
}
@AfroThundr3007730
Copy link
Author

Updated version available in my HelperFunctions module.

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