How to download last camera record via PowerShell from UniFi NVR API with SSL

This guide explains how to download latest camera record available on UniFi NVR server via Powershell through the REST API with SSL self-signed certificate.

Requirements:

  • UniFi NVR server
  • User API key (user must have admin role)
  • PowerShell v3+
  • Modify first 3 lines of script to meet your environment requirements

Script:

$NvrIP = "192.168.1.100" #Set IP of the NVR server
$ApiKey = "123XYZ098ABC" #Set Api key from NVR user accounts administration
$Output = "C:\temp\video.mp4" #Set location where to save video

try {
    #Ignore self-signed certificate
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

    #Create object WebClient .NET Class
    $wc = New-Object System.Net.WebClient

    #Download camera records from the WebClient
    $data = $wc.DownloadString("https://$($NvrIP):7443/api/2.0/recording?apiKey=$($ApiKey)") | ConvertFrom-Json

    #Find last camera record
    $LastIdRecord = $data.data._id | Select-Object -Last 1

    #Build URL string to download camera record
    $Url = "https://$($NvrIP):7443/api/2.0/recording/$($LastIdRecord)/download?apiKey=$($ApiKey)"

    #Download the camera record to the disk
    (New-Object System.Net.WebClient).DownloadFile($Url, $Output)
}
catch {
    Write-Error $_.Exception.Message
}

Some notes:

  • Why was not used directly PS cmdlet Invoke-restmethod?
    • Because with this cmdlet is not possible to specify ignore self-signed certificate. Then you need to use HTTP request which is not secure for our purpose to download video over the network.
  • Why was not used PS cmdlet Invoke-WebRequest as well?
    • This cmdlet gives nice progress bar but cons is speed. First HTTP stream will be saved to buffer and then saved to disk. This is much slower than .NET Class WebClient.

With help of this script you can automate your video records – for example send records to the backup server in case some burglar will steal your NVR camera records. Or upload video to Slack channel…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.