Powershell script to backup vApp machines using Veeam backup

These are just basic powershell scripts. You can use your own logic to enhance this.

cls
#Load vmware pssnapin

if(!(Get-PSSnapin | ?{$_.Name -eq "VMware.VimAutomation.Core"}))
{
    Add-PSSnapin VMware.VimAutomation.Core
}


#Define parameters

$vapp = $args[0]
Write-Output $vapp
$loghome = 'C:\script\Backups\'
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm"
$logfile = $loghome + "Backup_" + $logtime +".log"


#To dispaly message

Function Write-Log
{
   param ( [string]$message )
   $time = get-date -displayhint time
   Write-Host "$message"
   "[$time] $message" >> $logfile
}

#Connect to Vcenter

Connect-VIServer -Server 172.28.xx.xx -user username -Password password
Write-log "Connected to the Vcenter server"
write-Host
Write-log "Proceeding with the shutdown of vApp $($vapp)"
write-Host

#Stop vapp 

Get-VApp "$($vapp)" | Stop-VApp -confirm:$false

#Load Veeam pssnapin

if(!(Get-PSSnapin | ?{$_.Name -eq "VeeamPSSnapIn"}))
{
    Add-PSSnapin VeeamPSSnapIn
}

#Start Veeam Job


foreach ($job in $vbrjobs) 
{
   $jName = $job.Name
   write-Log "Starting job: $jName"
#give the backup job name
   start-vbrjob "$($vapp)_backup"   
}

write-Host
write-Log "Waiting for backups to complete"

#Error handling

do
{
   Start-Sleep -s 30
   $count = -1
   $count = (@(Get-VBRJob | ?{$_.Name -match "$($vapp)_backup"} | ?{$_.Control -eq "Start"})).Count
   write-host $count -NoNewline
} while ($count -gt 0)
write-host

$failedJobs = @(Get-VBRJob | ?{$_.Name -match "$($vapp)_backup"} | ?{$_.LatestStatus -ne "Success"})
if ($failedjobs.Count -gt 0)
{
   [string]$error = "Backup Failed"
   $failedJobs | %{ $error += ": "+$_.Name }
   throw $error
}
else
{
   write-Log "Backup completed successfully"
}

write-host (get-date) -ForegroundColor green
Write-log "vApp bootup in progress : $($vapp)"
write-Host
Write-log "vApp $($vapp) is now started"
Get-VApp "Script_vapp" | Start-VApp
Write-log "vApp $($vapp) bootup completed"

The vApp name will be given via a bat file:

set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Backuplog_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log
powershell.exe "C:\<script location>\Backup.ps1 vapp_name" >>C:\script\Backups\Consolelog_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log

Comments

Popular posts from this blog

VMware and Windows Interview Questions: Part 2

VMware and Windows Interview Questions: Part 3

VMware vMotion error at 14%