NewRelic.Download.psm1


<#
.Synopsis
    Downloads a file in a temp location
.Description
    Downloads a file in a temp location and provides the path back
.Example
    Get-TempDownload -DownloadURL 'https://nr.com...' -FileName 'agent.msi'
    Downloads the file from the URL with the name specified and returns the full path to the file in a temp directory.
.Parameter DownloadURL
    URL to download the file from
.Parameter FileName
    File name to download as
#>

function Get-TempDownload {
  [CMDLetBinding()]
  [OutputType([System.String])]
  Param (
    [Parameter (Mandatory = $true)]
    [string]$DownloadURL,
    [Parameter (Mandatory = $true)]
    [string]$FileName
  )

  # Check for and create temp folder
  $LocalPath = $env:Temp
  If (!(Test-Path $LocalPath)) {
    Throw "Temp path $LocalPath not found..."
  }

  # PowerShell 5.1 is very slow to download files because of progress output. This has been fixed in 7.0+
  # May need to tweak targeting version, but being very explicit for now as I would rather show the progress if possible
  if(($ProgressPreference -ne 'SilentlyContinue') -and ($PSVersionTable.PSVersion -like '5.1*')){
    Write-Verbose 'Changing ProgressPreference to speed up older versions of PowerShell downloads'
    $currentPreference = $ProgressPreference
    $ProgressPreference = 'SilentlyContinue'
    Write-Progress "Downloading file: $DownloadURL" -Id 0 # static replacement for progress
  }

  # Download
  Write-Verbose "Downloading: $DownloadURL"
  Invoke-RestMethod -ContentType 'application/octet-stream' -Uri $DownloadURL -OutFile "$LocalPath\$FileName"

  # Set Preference back if changed
  if($currentPreference){
    $ProgressPreference = $currentPreference
    Write-Progress 'Download Complete' -Id 0 -Completed
  }

  Return "$LocalPath\$FileName"
}