Files
management-scripts/Update-EmberkomCloudBackup.ps1
T

127 lines
6.9 KiB
PowerShell

#Requires -Version 5.1
# Update an existing Emberkom MSP360 Managed Backup agent during an idle RMM window.
function Get-CloudBackupAgent {
# MSP360's managed-agent registration points to the branded uninstall key.
# Open the registry view explicitly so a 32-bit RMM host can see a 64-bit agent.
$views = if ([Environment]::Is64BitOperatingSystem) { 'Registry64', 'Registry32' } else { 'Registry32' }
foreach ($view in $views) {
$registry = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', $view)
$marker = $product = $null
try {
$marker = $registry.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}')
if (!$marker) { continue }
$product = $registry.OpenSubKey([string]$marker.GetValue('UninstallKey'))
if (!$product -or !$product.GetValue('')) { throw 'The MSP360 agent registration has no executable path.' }
if ($product.GetValue('Publisher') -ne 'Emberkom') { throw 'The registered backup agent belongs to a different publisher.' }
$cli = Join-Path (Split-Path -LiteralPath $product.GetValue('')) 'cbb.exe'
return (Read-CloudBackupAgent -Cli $cli)
} finally {
if ($product) { $product.Dispose() }
if ($marker) { $marker.Dispose() }
$registry.Dispose()
}
}
}
function Read-CloudBackupAgent {
param([string]$Cli)
$details = & $Cli ver
if ($LASTEXITCODE -ne 0) { throw "MSP360 could not report the installed agent details (exit $LASTEXITCODE)." }
$edition = $service = $null
foreach ($line in $details) {
if ($line -match '^Backup Agent Edition:\s*(.+)$') { $edition = $Matches[1].Trim() }
if ($line -match '^Service name:\s*(.+)$') { $service = $Matches[1].Trim() }
}
if ($edition -in @('VMware','VMEdition','VM','Virtual Machine Edition')) {
$build = 'VM'
} elseif ($edition -in @('Desktop','DesktopIBB','FileBackup','BareMetal','Server','MsSql','SqlServer',
'Exchange','MsExchange','SqlExchange','MsSqlExchange','MsSqlMsExchange','Enterprise','Ultimate')) {
$build = 'Windows'
} else {
throw "Unrecognized MSP360 agent edition '$edition'. Cannot choose a published package."
}
if (!$service) { throw 'MSP360 did not report its backup service name.' }
[pscustomobject]@{
Version = [version][Diagnostics.FileVersionInfo]::GetVersionInfo($Cli).FileVersion
Build = $build
Service = $service
}
}
function Test-CloudBackupUpdateWindow {
param([string]$Window, [datetime]$Now = (Get-Date))
if ([string]::IsNullOrWhiteSpace($Window)) { return $true }
if ($Window.Trim() -notmatch '^((?:[01]\d|2[0-3]):[0-5]\d)-((?:[01]\d|2[0-3]):[0-5]\d)$') {
throw 'MSP360UpdateWindow must be a local 24-hour interval such as 12:00-13:00.'
}
$start = [timespan]::ParseExact($Matches[1], 'hh\:mm', $null)
$end = [timespan]::ParseExact($Matches[2], 'hh\:mm', $null)
if ($start -eq $end) { throw 'MSP360UpdateWindow needs different start and end times.' }
$time = $Now.TimeOfDay
if ($start -lt $end) { return ($time -ge $start -and $time -lt $end) }
return ($time -ge $start -or $time -lt $end)
}
function Test-CloudBackupPlanRunning {
# The agent launches CBBackupPlan.exe for plan execution. This also works on
# CLI-password-protected agents, without passing credentials to a child process.
return [bool](Get-CimInstance -ClassName Win32_Process -Filter "Name = 'CBBackupPlan.exe'" -Property ProcessId -ErrorAction Stop)
}
function Invoke-CloudBackupUpdate {
param([string]$Window)
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host "Deferred. Outside the local update window $Window."; return 0 }
$agent = Get-CloudBackupAgent
if (!$agent) { Write-Host 'Skipped. MSP360 Managed Backup is not installed.'; return 0 }
$release = Get-EmberkomCloudBackupRelease -Build $agent.Build
$target = [version]$release.Version
if ($agent.Version -ge $target) {
Write-Host "No update needed. Installed $($agent.Version), published $($agent.Build) build $target."
return 0
}
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker is active.'; return 0 }
$installer = Join-Path ([IO.Path]::GetTempPath()) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
try {
Write-Host "Downloading the published $($agent.Build) update from $($agent.Version) to $target."
Save-EmberkomCloudBackupInstaller -Release $release -Path $installer
# A scheduled plan or the agent's own updater could have started during download.
$current = Get-CloudBackupAgent
if (!$current -or $current.Build -ne $agent.Build) { throw 'The installed agent changed during download.' }
if ($current.Version -ge $target) { Write-Host "Already updated to $($current.Version)."; return 0 }
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host 'Deferred. The update window ended during download.'; return 0 }
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker started during download.'; return 0 }
$setup = Start-Process -FilePath $installer -ArgumentList '/S' -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($setup.ExitCode -eq 3010) { Write-Host 'MSP360 setup requires a restart to finish. Run the check again after restart.'; return 3010 }
if ($setup.ExitCode -ne 0) { throw "MSP360 setup returned exit code $($setup.ExitCode)." }
$updated = Get-CloudBackupAgent
if (!$updated -or $updated.Build -ne $agent.Build -or $updated.Version -lt $target) {
throw "Setup exited successfully but the installed $($agent.Build) agent could not be verified at $target or newer."
}
$service = Get-Service -Name $updated.Service -ErrorAction Stop
$service.WaitForStatus('Running', [timespan]::FromSeconds(60))
Write-Host "Updated MSP360 $($updated.Build) from $($agent.Version) to $($updated.Version). $($updated.Service) is running."
return 0
} finally {
if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction Stop }
}
}
$ErrorActionPreference = 'Stop'
$updateLock = [Threading.Mutex]::new($false, 'Global\EmberkomCloudBackupUpdate')
$ownsLock = $false
try {
try { $ownsLock = $updateLock.WaitOne(0) }
catch [Threading.AbandonedMutexException] { $ownsLock = $true }
if (!$ownsLock) { Write-Host 'Deferred. Another Emberkom Cloud Backup update check is running.'; exit 0 }
$windowInput = Get-Variable -Name MSP360UpdateWindow -ErrorAction SilentlyContinue
exit (Invoke-CloudBackupUpdate -Window ([string]$windowInput.Value))
} catch {
Microsoft.PowerShell.Utility\Write-Error "Emberkom Cloud Backup update failed. $($_.Exception.Message)" -ErrorAction Continue
exit 1
} finally {
if ($ownsLock) { $updateLock.ReleaseMutex() }
$updateLock.Dispose()
}