Created
April 3, 2023 18:41
-
-
Save AfroThundr3007730/c28dd17f582100fcf4a9ba18aa002c64 to your computer and use it in GitHub Desktop.
Powershell function to retrieve a file 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
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated version available in my HelperFunctions module.