Skip to content

Altaro VM Backup Alerts via Telegram

Altaro Telegram Hero

Alright, here’s the deal. This guide lays out how I keep tabs on Altaro VM Backup jobs without losing my mind.

It’s like this:

  • Ripping Altaro backup events straight outta Windows Event Log
  • Screaming at me on Telegram when backups fail
  • Dumping every single backup result — good, bad, or ugly into monthly .csv logs
  • Rolling up old logs into zip files so my server doesn’t look like a garage after band practice

The PowerShell script? It’s running live in production. It’s fully automated, kicking off on a schedule. Either way, it’s like having a drummer who’s always there to keep time.


Overview of the Workflow

Altaro Telegram Flow

The script pulls events (Event ID 5000–5003) from Altaro VM Backup, extracts key info, sends failed statuses to Telegram, and logs every job into a .csv. It rotates .csv logs into .zip after 365 days.


Log Output Structure

📁 altaro-stats-YYYY-MM.csv

Logs individual VM backup results.

Timestamp Host VM Status EventID RecordID Description
2019-06-26 08:00:11 TFH-IT-HV01 TFH-IT-PX02 Failed Backup 5002 165313 Backup Result: Failed Backup ...

📁 altaro-runlog-YYYY-MM.csv

Logs each script execution.

Timestamp Host Username Status Note
2019-06-27 00:10:01 TFH-IT-HV01 SYSTEM Skipped No new events found
2019-06-27 02:00:01 TFH-IT-HV01 Administrator Success Script executed with 3 events

Script Features

Telegram Alerting

  • Only non-successful events are sent
  • Message includes VM name, status, event ID, time, and host
  • Note: If Telegram API errors occur, they are written only as console warnings, not to the CSV logs.

RecordID Tracking

  • Prevents duplicate alerts by tracking the last processed RecordId
  • Skips previously processed events during normal runs

Force Scan Mode

  • Use -ForceScan -LookbackHours N to manually recheck recent logs
  • Useful when RecordId logic might miss out-of-sequence logs
  • Note: Running -ForceScan resets the tracking and may send duplicate alerts for older events already processed.

Logging & Archiving

  • Writes all VM backup statuses to monthly altaro-stats-YYYY-MM.csv
  • Writes each script run (manual or scheduled) to altaro-runlog-YYYY-MM.csv
  • Logs older than 365 days (based on last modified date) are auto-compressed

Running the Script

Regular Execution (Task Scheduler or manual)

PowerShell
pwsh -ExecutionPolicy Bypass -File "C:\Scripts\Altaro Notification\altaro-telegram.ps1"

Manual Force Scan (to recover missed logs)

PowerShell
pwsh -ExecutionPolicy Bypass -File "C:\Scripts\Altaro Notification\altaro-telegram.ps1" -ForceScan -LookbackHours 2

Task Scheduler Setup

To run the script automatically whenever a relevant Altaro VM Backup event is logged:

  1. Open Task Scheduler and create a new task.
  2. Under General, set it to run with highest privileges.
  3. Under Triggers, click New:

  4. Begin the task: On an event

  5. Log: Application
  6. Source: Altaro VM Backup
  7. Event IDs: 5000, 5001, 5002, 5003
  8. Under Actions, click New:

  9. Action: Start a program

  10. Program/script: pwsh (or powershell.exe if you're not using PowerShell Core)
  11. Add arguments: -ExecutionPolicy Bypass -File "C:\\Scripts\\Altaro Notification\\altaro-telegram.ps1"
  12. Under Conditions and Settings, adjust based on your preference (e.g., disable idle checks, retry on failure, etc.)

This ensures alerts are sent immediately when Altaro logs a new backup event.


Log Rotation Policy

File Pattern Rotation Method Retention
altaro-stats-YYYY-MM.csv Compress to .zip 365 days old (last modified)
altaro-runlog-YYYY-MM.csv Compress to .zip 365 days old (last modified)

Logs are archived using Compress-Archive and deleted after compression. Existing .zip files are left untouched.


Example Telegram Message

📢 Altaro • Notification

🖥️ Host : TFH-IT-HV01
🕒 Time : 2019-06-26 08:00:11
📦 VM   : TFH-IT-PX02
🎲 State : 💀 Error
🎯 Event : 5002

📝 Backup Result: Failed Backup - The Backup for this VM could not take place because it is no longer running on host TFH-IT-HV01...

🧠 AltaroBot™

Tips for Production Use

  • Run it hourly via Task Scheduler
  • Monitor the altaro-runlog-*.csv for skipped events
  • Use -ForceScan after crashes or missed alert windows
  • Always update BotToken and ChatID before deployment
  • Script supports both pwsh (PowerShell Core) and classic powershell.exe

Full Script

Click to expand the full altaro-telegram.ps1 script
PowerShell
param(
    [switch]$ForceScan,
    [int]$LookbackHours = 2
)

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# ========== CONFIG ==========
$BotToken = "your_bot_token"
$ChatID   = "your_chat_id"
$APIUrl   = "https://api.telegram.org/bot$BotToken/sendMessage"

$ThisHost  = $env:COMPUTERNAME
$Now       = Get-Date
$MonthTag  = $Now.ToString("yyyy-MM")
$LogDir    = "C:\Scripts\Altaro Notification\Log"
$LogFile   = Join-Path $LogDir "last-event-id.txt"
$CSVFile   = Join-Path $LogDir "altaro-stats-$MonthTag.csv"
$RunLogCSV = Join-Path $LogDir "altaro-runlog-$MonthTag.csv"
$LogTTL    = $Now.AddDays(-365)

# ========== INIT ==========
if (-not (Test-Path $LogDir))  { New-Item -ItemType Directory -Path $LogDir | Out-Null }
if (-not (Test-Path $LogFile)) { New-Item -ItemType File -Path $LogFile | Out-Null }

$LastRecordID = Get-Content $LogFile -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $LastRecordID) { $LastRecordID = 0 }

if ($ForceScan) {
    Write-Host "⚠️ Force scan mode enabled. Scanning logs from last $LookbackHours hour(s)..."
    $SafeWindow = $Now.AddHours(-$LookbackHours)
    $LastRecordID = 0  # ignore RecordId in this mode
} else {
    $SafeWindow = $Now.AddMinutes(-15)
}

# ========== FETCH EVENTS ==========
$Events = Get-WinEvent -FilterHashtable @{
    LogName      = 'Application'
    ProviderName = 'Altaro VM Backup'
    Id           = 5000,5001,5002,5003
} | Where-Object {
    $_.RecordId -gt [int64]$LastRecordID -or $_.TimeCreated -gt $SafeWindow
} | Sort-Object TimeCreated

foreach ($e in $Events) {
    $msg       = $e.Message -replace '[\r\n]+', ' | '
    $time      = $e.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")
    $rawtime   = $e.TimeCreated.ToString("s")
    $recordId  = $e.RecordId
    $eventID   = $e.Id
    $parsedOK  = $false

    if ($msg -match 'Guest VM Name:\s*(.+?)\s*\|\s*(Backup|Restore) Result:\s*(.+?)\s*\|\s*(.+?)\s*operation started at') {
        $vmName = $Matches[1]
        $type   = $Matches[2]
        $status = $Matches[3]
        $desc   = "$type Result: $status"
        $parsedOK = $true

        switch -Regex ($status.ToLower()) {
            'success'      { $emoji = "✅"; $level = "Success" }
            'fail|error'   { $emoji = "💀"; $level = "Error" }
            'warning'      { $emoji = "⚠️"; $level = "Warning" }
            default        { $emoji = "❓"; $level = $status.ToLower() }
        }

        if ($level -eq "Success") {
            # Skip Telegram for success, log to CSV only
            $csvEntry = [PSCustomObject]@{
                Timestamp   = $rawtime
                Host        = $ThisHost
                VM          = $vmName
                Status      = $status
                EventID     = $eventID
                RecordID    = $recordId
                Description = $desc
            }

            $append = Test-Path $CSVFile
            $csvEntry | Export-Csv -Path $CSVFile -Append:$append -NoTypeInformation
            Set-Content -Path $LogFile -Value $recordId
            continue
        }

# ========== TELEGRAM MESSAGE ==========
$text = @"
📢 Altaro • Notification

🖥️ Host : $ThisHost
🕒 Time : $time
📦 VM : $vmName
🎲 State : $emoji $level
🎯 Event : $eventID

📝 $desc

🧠 AltaroBot™
"@

        try {
            Invoke-RestMethod -Uri $APIUrl -Method Post -ContentType "application/json" -Body (@{
                chat_id = $ChatID
                text    = $text
            } | ConvertTo-Json -Depth 3)
        }
        catch {
            Write-Warning "❌ Failed to send Telegram alert: $_"
        }

        # Write to CSV
        $csvEntry = [PSCustomObject]@{
            Timestamp   = $rawtime
            Host        = $ThisHost
            VM          = $vmName
            Status      = $status
            EventID     = $eventID
            RecordID    = $recordId
            Description = $desc
        }

        $append = Test-Path $CSVFile
        $csvEntry | Export-Csv -Path $CSVFile -Append:$append -NoTypeInformation
    }

    if (-not $parsedOK) {
        Write-Warning "⚠️ Skipped RecordId $recordId — unrecognized format: $($msg.Substring(0, 80))..."
    }

    # Always update last seen RecordId to move forward
    Set-Content -Path $LogFile -Value $recordId
}

# ========== LOG SCRIPT EXECUTION ==========
$runStatus = if ($Events.Count -eq 0) { "Skipped" } else { "Success" }
$runNote   = if ($Events.Count -eq 0) { "No new events found" } else { "Script executed with $($Events.Count) events" }

$runLogEntry = [PSCustomObject]@{
    Timestamp = $Now.ToString("yyyy-MM-dd HH:mm:ss")
    Host      = $ThisHost
    Username  = $env:USERNAME
    Status    = $runStatus
    Note      = $runNote
}

$append = Test-Path $RunLogCSV
$runLogEntry | Export-Csv -Path $RunLogCSV -Append:$append -NoTypeInformation

# ========== ROTATE OLD LOGS ==========
Get-ChildItem -Path $LogDir -Filter "altaro-stats-*.csv" | Where-Object {
    $_.LastWriteTime -lt $LogTTL
} | ForEach-Object {
    $zipPath = "$($_.FullName).zip"
    Compress-Archive -Path $_.FullName -DestinationPath $zipPath -Force
    Remove-Item $_.FullName
}

Get-ChildItem -Path $LogDir -Filter "altaro-runlog-*.csv" | Where-Object {
    $_.LastWriteTime -lt $LogTTL
} | ForEach-Object {
    $zipPath = "$($_.FullName).zip"
    Compress-Archive -Path $_.FullName -DestinationPath $zipPath -Force
    Remove-Item $_.FullName
}

Tip

For security, remove hardcoded tokens if committing this to version control.


Conclusion

This script’s the ugly truth hiding in the corner. It stays silent until the lights buzz and the walls start sweating. Then it screams so you know your backups didn’t rot away while you weren’t looking. It’s scarred, scraped, and running on fumes, but it keeps watch like a beat-up guitar that still plays the right chords when you hit it hard enough.

For the sysadmins burning through coffee and nicotine, chasing down ghosts in logs at 2am, this PowerShell riff is your battered lifeline.

Keep the noise alive. Keep the rust showing. And don’t let your backups vanish like cigarette smoke. 🤘