functions/Get/Get-FilesFromGithub.ps1
function Get-FilesFromGithub { <# .SYNOPSIS This function retrieves the specified repository on GitHub to a local directory with authentication. .DESCRIPTION This function retrieves the specified repository on GitHub to a local directory with authentication, being a single file, a complete folder, or the entire repository. .PARAMETER Owner Owner of the repository you want to download from. .PARAMETER Repository The repository name you want to download from. .PARAMETER FileName The path inside the repository you want to download from. If empty, the function will iterate the whole repository. Alternatively you can specify a single file. .PARAMETER Destination The local folder you want to download the repository to. .PARAMETER Ref The name of the commit/branch/tag. Default: the repository’s default branch (usually master) .PARAMETER AsZip Uses github zipball to download whole repository .EXAMPLE PS C:\> Get-FilesFromGithub -Owner "test" -Repository "SomeRepo" -Path YYY/InternalFolder/test.ps1" -Destination "C:/MyDownloadedRepository" -Ref 'feature/test' #> Param( [Parameter(Mandatory = $false)] [string]$Owner = 'lineupsystems', [Parameter(Mandatory = $true)] [string]$Repository, [Parameter(Mandatory = $true)] [AllowEmptyString()] [string]$Path, [Parameter(Mandatory = $false)] [string]$Destination, [Parameter(Mandatory = $false)] [string]$Ref ) begin { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $baseUri = "https://api.github.com"; $headers = Get-GithubHeaders # If Ref is not passed then load it from customer config $Ref = Get-DefaultBranch -Ref $Ref } process { # REST Building $argsUri = "repos/$Owner/$Repository/contents/$($Path)?ref=$Ref"; $response = Invoke-WebRequest -Uri ("$baseUri/$argsUri") -Headers $headers -UseBasicParsing -ErrorAction Stop # Data Handler $objects = $response.Content | ConvertFrom-Json $files = $objects | Where-Object {$_.type -eq "file"} | Select-Object -exp download_url $directories = $objects | Where-Object {$_.type -eq "dir"} # Iterate Directories $directories | ForEach-Object { Get-FilesFromGithub -Owner $Owner -Repository $Repository -Path $_.path -Destination "$($Destination)/$($_.name)" -Ref:$Ref } if (-not (Test-Path $Destination)) { New-Item -Path $Destination -ItemType Directory -ErrorAction Stop | Out-Null } foreach ($file in $files) { $outputFilename = (Join-Path $Destination (Split-Path $file -Leaf)) -replace '\?.*', '' $targetDir = Split-Path $outputFilename if (-not (Test-Path $targetDir)) { New-Item -Path $targetDir -ItemType Directory -ErrorAction Stop | Out-Null } Invoke-WebRequest -Uri $file -OutFile $outputFilename -ErrorAction Stop } } } |