Friday, January 5, 2018

Get Last Backup Field in vCenter with Powershell.

#This is a little Powershell script that gets the last time a vm in the Cluster that it has been backed up.  Emails out if it has not been backed up in 14days.

$daystoalert = 14
$vCenter = "vCenter server name"

add-pssnapin vmware.vimautomation.core
connect-viserver $vCenter
$today_date = get-date

$all_vms = get-cluster "Cluster Name" | get-vm | Sort-Object Name

foreach($vm in $all_vms)
{
    #check $vm for null?
    Try {
        $last_backup_date = $vm. CustomFields.Get_Item( "Last Backup")
        $last_backup_converted = get-date $last_backup_date
        $days_with_no_backups = New-TimeSpan -Start $last_backup_converted .DateTime -End $today_date. DateTime
        if ($days_with_no_backups .Days -gt $daystoalert)
        {
            Write-output " $($vm. Name),$( $days_with_no_backups.Days) "
        }
    }
    Catch {
        # VM was never backed up gets caught in this exception.
        Write-output " $($vm. Name), Never backed up"
    }