Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Powershell Script to download backup from a Ubiquiti UniFi Controller or Cloud Key
Author: Shannon Brooks
Date: Dec 1st, 2016
Licence: Creative Commons Attribution-ShareAlike 4.0 International License
License URL:
Downloads a backup file from a UniFi controller
Downloads a backup file from a UniFi controller using the (undocumented) UniFi controller API
C:\PS> .\Get-UniFiBackup.ps1 -Server 'localhost' -Port 8443 -Username 'admin' -Password 'XXXXXXXX' -BackupDays -1
Will download a full backup from the server 'localhost'
Server name or IP address
Server HTTPS port
Admin user to login with
Password for the admin user
.PARAMETER BackupLocation
Location to save the backups, will be created if it doesn't exist
Number of days of data to retain in the backup
Values in UniFi interface are 7, 30, 60, 90, 180, 365, and -1 (unlimited)
.PARAMETER BackupTimeStampFormat
Format for backup time stamp
See Get-Date for formatting options
.PARAMETER AcceptOnlyValidCertificates
Reject invalid or self signed SSL certificates
# make sure backup location exists
$BackupLocation = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($BackupLocation)
If ( -not ( Test-Path -Path $BackupLocation -PathType Container -ErrorAction SilentlyContinue ) )
New-Item -Path $BackupLocation -ItemType Directory -ErrorAction Stop
# accept all SSL certs
If ( -not ( $AcceptOnlyValidCertificates.IsPresent ) )
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
# construct server base URI
$BaseURI = 'https://' + $Server + ':' + $Port
# login
$Response = Invoke-RestMethod `
-Method Post `
-Uri "$BaseURI/api/login" `
-Body $( @{ username=$Username; password=$Password } | ConvertTo-Json ) `
-SessionVariable 'UniFiSession'
If ( $Response.meta.rc -ne 'ok' ) { Write-Error "LOGIN ERROR" -ErrorAction Stop }
# generate the backup file
$Response = Invoke-RestMethod `
-Method Post `
-WebSession $UniFiSession `
-Uri "$BaseURI/api/s/default/cmd/system" `
-Body $( @{ cmd='backup'; days=$BackupDays } | ConvertTo-Json )
# download the backup file
Invoke-WebRequest `
-Uri "$BaseURI$($" `
-WebSession $UniFiSession `
-OutFile "$BackupLocation\$Server`_$(Get-Date -f $BackupTimeStampFormat).unf"
# logout
$Response = Invoke-WebRequest `
-Uri "$BaseURI/logout" `
-WebSession $UniFiSession
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment