PowerShell script exchange
Post Reply
adb98
Enthusiast
Posts: 63
Liked: 13 times
Joined: Jul 21, 2016 5:03 pm
Full Name: Aaron B
Contact:

Quick Backup/ Job Backup Automation Script

Post by adb98 » 2 people like this post

We have been using Veeam for a few years now and each release I pray that they would fix "one off" backup requests by adding scheduling and maybe even a self service portal like we have for restores. Each new release though I am met with disappointment. We get at least 2 to 3 request a week from various application teams requesting a backup of a certain VM or several VMs that need to be backed up at a certain time. "Quick backups" only fills part of that need. You still need be at the console to kick it off and have to stay at the console to ensure it finished without an issue to alert the user that they are all set.

To fix this I spent a good chunk of time and wrote a Powershell script that should take care of these types of request automatically. Long story short... This will run a "quick backup" or a "full job", email you with the start results, and then email you again once the backup has finished. To automate this simply setup a scheduled task in taskmgr with the parameters and set a time to run. It will do the rest.

I am no expert in Powershell and I am sure there is a better way with some of my code so feel free to add to it if it can be improved. Just be sure to post so we all benifit.

Code: Select all

<#
.SYNOPSIS
    This script is used with Windows Scheduled on the main VBR server to  tasks to take "quick backups" of individual VMs and "whole job" at scheduled times

.DESCRIPTION
    This was built to compensate for the lack of individual VM and one time scheduled job backups. This allows a "quick backup" or "whole job" to have a one time seperate run time other than when it normally runs. 
    Furthermore this sends notifications via email so you don't have to go to the console to check wither it started and wither it finished. Setup in scheduled task and its ready to go. 

.PARAMETER VM
   -VM 
   A single Computer or an array of computer names.  Seperate with comma.


.PARAMETER Job
    -job
     This is for a whole job backup. Use quotes and comma for more than one

.PARAMETER TO
    -to
    This is the email address to send the notifications to. This is required as this is the only way the script alerts. There are not outputs when this script is run. 

.EXAMPLE
    Backup one VM
    PS C:\> veeam_quick_backup.ps1 -vm "server1" -to email@address

    Backing up several VMs
    PS C:\> veeam_quick_backup.ps1 -vm "server1","server2" -to email@address

    ##For the scheduled task in windows it would be setup as such. See internet examples for setting up a details on setting up a powershell script for a scheduled task.##

      <Command>powershell.exe</Command>
      <Arguments>-file C:\scripts\test\Veeam_Quick_Backup_automate.ps1 -vm servername -to email@address</Arguments>

      This will start the quick backup and send an email out stating wither it was successfull or not

.EXAMPLE
    Backing up one full job
    PS C:\> veeam_quick_backup.ps1 -job "Exchange servers" -to email@address

    Backing several jobs 
    PS C:\> veeam_quick_backup.ps1 -job "Exchange servers","AD servers","SQL Servers" -to email@address
    
.NOTES
    Author:  Aaron Belisle
    Email:   PM me via forum
    Date:    10AUG2018
    PSVer:   2.0/3.0/4.0/5.0
    Updated: 24AUG2018
    V2 - Added logic for emailing results of the backup out to the user. This was accomplished with DO/Then statements
    V2.1 - Added | ft -hidetableheaders to select states gathering objectIDs as it was adding a header for GUID
    Even with -expandproperty option
    V2.2 - Bug fixes and cleanup
    1. Removed double IFs in job and VM section as elseif will handle the progression
    2. For Job section, I added code to email if the name is not valid and then not progress with the script.
    V3 -Rebuild job section fixing checks and cleaning up IFs. I also had to add foreach to pull the status for each job if there were multiples so it send one email with all job results.
    Rewrote Job processing to help with efficientcy.            
#> 
    
#Parameters that are passed    
   
Param

([parameter(ValueFromPipeLineByPropertyName = $true, Mandatory = $false)][string[]]$vm,
    [parameter(ValueFromPipeLineByPropertyName = $true, Mandatory = $false)][string[]]$job,
    [parameter(ValueFromPipeLineByPropertyName = $true, Mandatory = $true)][string[]]$to
)

#Variables for Script
#-----------------------
#server Info
$Veeam_Server = "VBR Server"

#email Info
$from = "Email@From.local"
$smtp_server = "SMTPserver"
#---------------------------------------

#start collection bucket for outputs going to email for the start of jobs and the status of the start
$output = @()
#----------------------------------------------------------------------------
#Loading Veeam Snapin Piece and Veeam Connection to the server - If it is not registered it tells you and stops the script. Once the Snappin is loaded it trys to connect to the VBR Server

If (!(Get-PSSnapin -Name VeeamPSSnapIn -ErrorAction SilentlyContinue)) {
    If (!(Add-PSSnapin -PassThru VeeamPSSnapIn)) {
        $Output += "****Automated Scheduled VM backup failed. Unable to load Veeam snapin needed to run script***"
        $body = $output |Out-String
        Send-MailMessage -to $to -from $from -SmtpServer $smtp_server -Body $body -Subject "***Automated Scheduled VM backup was unsuccessful - See Below***"
        Exit
    }
}

#This trys a simple commmand to see if we are already connected to the VBR server. If it fails the commmand, then it tries to connect. Uses hashed creds
try {
    ((Get-VBRServer -name $Veeam_Server -ErrorAction SilentlyContinue) -eq $null)*>$null
}
catch {
    (Connect-VBRServer -server $Veeam_Server -Credential $MyCredentials)
}  
#--------------------------------------------------------------------------------

#This piece is where we check the server names given and ensure all is ok and run the script. It does this for each job.

#-------------------------
#Session ID capture bucket
#-------------------------

$SessionID = @()

#------------------------------
##VM Processing Section###
#------------------------------

foreach ($c in $vm) {
    if ((Find-VBRViEntity -Name $c) -eq $null) {
        $Output += write-output "***Automated Scheduled VM backup failed!!!! The following server name $c is not a valid server name. The following servers names below are a close match to what you might be looking for. Rerun script again with correct name or kick of backup via the VBR Console***"
        ($Output += Find-VBRviEntity -Name "*$c*" |Select-Object Name)
        $body = $output |Out-String
        Send-MailMessage -to $to -from $from -SmtpServer $smtp_server -Body $body -Subject "***Automated Scheduled VM backup was unsuccessful - See Below***"
        Exit
    }
    elseif ((Find-VBRViEntity -Name $c |Start-VBRQuickBackup -ErrorAction SilentlyContinue) -eq $null) {
        $Output += write-output "***Automated Scheduled VM backup failed!!! Backup Job with $c in it already running! Check VBR Console***"
        $jobname = get-VBRBackupSession | Where-Object {$_.JobType -eq "backup" -and $_.Isworking -eq "True"} | Get-VBRTaskSession | Where-Object -Property name -EQ "$c" |Select-Object -ExpandProperty jobname
        $SessionID += Get-VBRBackupSession | Where-Object {$_.Isworking -eq "True" -and $_.Jobtype -eq "Backup" -and $_.jobname -eq "$jobname"} | Select-Object -ExpandProperty Currentpointid
        break
    }
    else {
        $Output += write-output  "***Automated Scheduled VM backup for $c has been started successfully. You will recieve a second email once the backup is completed successfully. ***"
        start-sleep -Seconds 10
        $jobname = get-VBRBackupSession | Where-Object {$_.JobType -eq "backup" -and $_.Isworking -eq "True"} | Get-VBRTaskSession | Where-Object -Property name -EQ "$c" |Select-Object -ExpandProperty jobname
        $SessionID += Get-VBRBackupSession | Where-Object {$_.Isworking -eq "True" -and $_.Jobtype -eq "Backup" -and $_.jobname -eq "$jobname"} | Select-Object -ExpandProperty Currentpointid
    }
}

#---------------------
##Whole Job Section##
#---------------------

foreach ($j in $job) {

    try {
        $Jobinfo = Get-VBRJob | Where-Object {$_.name -eq "$j"}
        $JobpreStatuscheck = $Jobinfo.GetLastState() 
    }
    catch { 
        $Output += "Job Name $j is not valid. These jobs below are a close match to what you might be looking for. Once you got the correct name run it again."
        $Output += get-vbrjob -Name "*$j*" |Select-Object Name
        $body = $output |Out-String
        Send-MailMessage -to $to -from $from -SmtpServer $smtp_server -Body $body -Subject "***Automated Whole job backup was unsuccessful - See Below***"
        Exit
    }
    
    if ($JobpreStatuscheck -EQ "Working") {
        $Output += "Job already running grabbing Session ID and moving on. Will email once acitve job already in progress is complete"
        $SessionID += Get-VBRBackupSession | Where-Object {$_.Isworking -eq "True" -and $_.Jobtype -eq "Backup" -and $_.jobname -eq "$j"} | Select-Object -ExpandProperty Currentpointid
        break
    }
    else {
        Start-VBRJob -RunAsync $j |Out-Null
        $Output += "***Automated Whole job backup was successfully started for job **$j**. You will recieve a second email once the backup is completed successfully.***"
        start-sleep -Seconds 10
        #sleep is used to ensure job is started as if it is not started it will not pull and complete notification will not go out
        $SessionID += Get-VBRBackupSession | Where-Object {$_.Isworking -eq "True" -and $_.Jobtype -eq "Backup" -and $_.jobname -eq "$j"} | Select-Object -ExpandProperty Currentpointid
    }    
}
    
#---------------------------------------------------------------
#This sends 1st email notification telling the status of the job
#---------------------------------------------------------------

$body = $output |Out-String

$MailMessage = @{ 
    To          = $to
    From        = $from
    Subject     = "Veeam Automated VM Backup Request" 
    Body        = "$body"
    Smtpserver  = $smtp_server
    ErrorAction = "SilentlyContinue" 
}
Send-MailMessage @MailMessage

#---------------------------------------------------------------
#portion where we monitor for completion of the backups. The do prevents the script from moving on until all jobs are completed so only one email is sent. 
#---------------------------------------------------------------

Foreach ($Session in $SessionID) {

    do {
        $bustatus = Get-VBRBackupSession | Where-Object {$_.Currentpointid -eq "$session" -and $_.Jobtype -eq "Backup" -and $_.iscompleted -eq "true"} | Select-Object -ExpandProperty iscompleted
    }
    until($bustatus -eq "true")

}

$output1 = @()

Foreach ($Session in $SessionID) {

    $output1 += Get-VBRBackupSession | Where-Object {$_.Currentpointid -eq "$session" -and $_.Jobtype -eq "Backup"} | Select-Object jobname, baseprogress, iscompleted |Format-list
}

$body = $output1 |Out-String

$MailMessage = @{ 
    To          = $to
    From        = $from
    Subject     = "Veeam Automated VM Backup Request $job $VM - Completed " 
    Body        = "See Results Below $body"
    Smtpserver  = $smtp_server
    ErrorAction = "SilentlyContinue" 
}
Send-MailMessage @MailMessage
exit

MichaelCade
Veeam Software
Posts: 314
Liked: 74 times
Joined: Mar 23, 2015 11:55 am
Full Name: Michael Cade
Location: Cambridge, United Kingdom
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by MichaelCade »

Do your application owners have access at all to your vSphere vCenter with limited access to their application servers? The Veeam vSphere Web Client may be an answer here also - https://helpcenter.veeam.com/docs/backu ... tml?ver=95

This would allow for a right click on the VM and allow for an ad-hoc backup.

Image
Regards,

Michael Cade
Global Technologist
Veeam Software
Email: Michael.Cade@Veeam.com
Twitter: @MichaelCade1
adb98
Enthusiast
Posts: 63
Liked: 13 times
Joined: Jul 21, 2016 5:03 pm
Full Name: Aaron B
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by adb98 »

I have this setup and running but most of our users are application support members. They support applications in our hospitals. They don't ever touch Vcenter and only a few even know how to get into it.

Even if they did know how to use it, this method has huge limitations like not being able to do a full job, cumbersome task to do several VMs, limited notifications on failure or completion, trust in the end user to have chosen the correct VM and that it finished.

I rather leave this task to us (Sys Admins) to ensure it was done correctly and on time. Nothing worse than needing a restore and finding out they either forgot to take a backup, backed up the wrong VM, or it failed and they didn't notice.
MichaelCade
Veeam Software
Posts: 314
Liked: 74 times
Joined: Mar 23, 2015 11:55 am
Full Name: Michael Cade
Location: Cambridge, United Kingdom
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by MichaelCade »

I hear you.

Let me explore if there are any other avenues.
Regards,

Michael Cade
Global Technologist
Veeam Software
Email: Michael.Cade@Veeam.com
Twitter: @MichaelCade1
MichaelCade
Veeam Software
Posts: 314
Liked: 74 times
Joined: Mar 23, 2015 11:55 am
Full Name: Michael Cade
Location: Cambridge, United Kingdom
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by MichaelCade »

So who initiates this script you have created?

application support members? or sysadmins?
Regards,

Michael Cade
Global Technologist
Veeam Software
Email: Michael.Cade@Veeam.com
Twitter: @MichaelCade1
adb98
Enthusiast
Posts: 63
Liked: 13 times
Joined: Jul 21, 2016 5:03 pm
Full Name: Aaron B
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by adb98 »

We initiate it. It is really simple with the script since we already have a "run once" scheduled task on the VBR server. We simply modify it with the date and time we need and change the run string to meet what we want to backup and we are ready to go. That time comes, it kicks off, and notifications go out once it starts and once its complete. This has saved us so much time and worry that we will miss a request as we don't need to be at our desks. We just send an email to the user notifying them its done once we receive the email. I even updated the script on my end to have an optional param for "from" so we can have it send the started and completed emails to the user and set the from to look like it came from our team (or anyone that matter) so any replies from the user go to a live email.
pkelly_sts
Veteran
Posts: 600
Liked: 66 times
Joined: Jun 13, 2013 10:08 am
Full Name: Paul Kelly
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by pkelly_sts »

I'll add a vote for this functionality. I did have my own script but it appears to have stopped working for some reason (despite being much simpler/more basic than this one) so searching led me here.

Our scenario is, app users are doing an application update which affects only a subset of servers so they want a quick backup of those servers at a specific time just before they're scheduled to start their tasks.

Likewise, it's too cumbersome to do 6 VMs via the web client.

The perfect solution for me would be:

Right-click the specific VMs (as currently)
Select "Quick Backup (Scheduled)"
Get a scheduling dialog & simply enter date & time.
OK, QB job scheduled.
PTide
Product Manager
Posts: 6408
Liked: 724 times
Joined: May 19, 2015 1:46 pm
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by PTide »

Hi,

Maybe that's not exactly what you want, but now you can literally do the following:
1. Right-click the specific VMs (as currently)
2. Select "Add to backup job"
3. Enter name on the first step.
4. Skip "Next-next-next" ...wait, hold on! Define schedule.
5. Next, apply finish, done!

Thanks!
adb98
Enthusiast
Posts: 63
Liked: 13 times
Joined: Jul 21, 2016 5:03 pm
Full Name: Aaron B
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by adb98 »

I could create a new job for a one time scheduled backup and then delete that job once it finished but that would create a new full when it ran for the first time and you would have to manage when the retention fell off and the backup was deleted.

There should be a "quick backup" option under jobs where you can schedule one offs. Its cool to have quick backups but when you have to literally have to be in front of the console to do so and constantly watch it to ensure all is ok, it is a huge limitation. Creating a new job is an answer but not very efficient.
pkelly_sts
Veteran
Posts: 600
Liked: 66 times
Joined: Jun 13, 2013 10:08 am
Full Name: Paul Kelly
Contact:

Re: Quick Backup/ Job Backup Automation Script

Post by pkelly_sts »

PTide wrote: Nov 16, 2018 6:44 pm Maybe that's not exactly what you want, but now you can literally do the following:
Thanks!
Yeah, not really what we'd want at all - we'd just want to run a quick backup prior to doing some planned work (e.g. friday was a big in-house application update where the app owners wanted a roll-back option for 8 VMs already in the main job, one of which was 600Gb total server size. I just did a manual quick backup which took <10 mins for all 8 servers - it would have taken significantly longer to do a one-off full backup of the same in the manner you describe above.
Post Reply

Who is online

Users browsing this forum: No registered users and 18 guests