Assert-FfmpegIsPresent.ps1

function Assert-FfmpegIsPresent
{
  <#
      .SYNOPSIS
      Returns the path to the ffmpeg.exe executable. If the executable is not present, it will be automatically downloaded (on Windows), or a message appears with instructions on how to install it (on other OS).
 
      .DESCRIPTION
      ffmpeg.exe is a free open-source tool to perform audio file format conversions.
 
      .PARAMETER ExecutablePath
      Optional. When specified, the executable is expected at this path, and when missing, will be downloaded to this path.
      When not specified, the default location is $env:temp\ffmpeg\ffmpeg.exe
 
      .PARAMETER Force
      Downloads the tool even if it exists already (i.e. to ensure the latest version)
 
      .EXAMPLE
      $path = Assert-FfmpegIsPresent
      returns the path to ffmpeg.exe so it can then be called.
  #>



  [CmdletBinding()]
  param
  (
    [String]
    $ExecutablePath = (Join-Path $env:temp -ChildPath ffmpeg | Join-Path -ChildPath ffmpeg.exe),
    
    [switch]
    $Force
  )
  
  $exists = Test-Path -Path $ExecutablePath
  if ($exists -and (!$Force)) { return $ExecutablePath }
  
  $windows = Test-IsWindows
  if ($windows)
  {

    $url = 'https://github.com/ffbinaries/ffbinaries-prebuilt/releases/download/v6.1/ffmpeg-6.1-win-64.zip'
    $archive = Join-Path -Path $env:temp -ChildPath ffmpeg.zip
    $archiveUnpacked = $ExecutablePath | Split-Path 
    Write-Host "ffmpeg.exe not present, downloading (52KB)..."
    Invoke-WebRequest -Uri $url -OutFile $archive -UseBasicParsing
    Unblock-File -Path $archive
    Write-Host "Unpacking downloaded archive..." -NoNewline
    Expand-Archive -Path $archive -DestinationPath $archiveUnpacked -Force
    Remove-Item -Path $archive 
    $exists = Test-Path -Path $ExecutablePath
    if ($exists)
    {
      Write-Host "success."
    }
    else
    {
      Write-Host "failed: unable to write to $ExecutablePath"
    }
  }
  
  if ($exists)
  {
    return $ExecutablePath
  }
  else
  {
    Write-Host @'
You need to manually download "ffmpeg.exe" from here: https://ffbinaries.com/downloads
After you have downloaded the archive, unblock and unpack it, and move ffmpeg.exe (not ffprobe.exe!) to this location:
'@

    Write-Host $ExecutablePath -ForegroundColor Black -BackgroundColor White
    throw "ffmpeg.exe not found: $ExecutablePath does not exist."
  }
  
}