Get-SrmEvents.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID 1e0439af-b40f-44a9-860d-4a579b29c1e4
 
.AUTHOR Shihan Pietersz
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS vmware powercli srm srmreplication vm
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES VMware.VimAutomation.Core
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 Get vmware srm replication state
 
#>
 


#Requires -Version 5.0
#Requires -RunAsAdministrator
#Requires -Modules VMware.VimAutomation.Core
#Name : Get-SrmEvents

#Created By: Shihan Pietersz
#Date: 08/09/2017
#Purpose: Check vmware replication issues
#TestedON: Vmware 5.5 and SRM 5.8

<#
 
.SYNOPSIS
The Script will connect to a existing vSphere and SRM infrastructure and check SRM replication health of virtual machines
 
.DESCRIPTION
Check the health status of SRM and report back.
at the end of the script fill, in the parameters to run.
 
all output will be written to console and log files. Two types of log files will be created .log and .csv
 
the .log file contains information if the SRM protected vm is protected or in error
the .csv file contains basic VM information and SRM replication information
 
 
.EXAMPLE
./Get-SRMEventInfo -VcenterServer "VmwareVsphere01.vsphere.local" -LogFileFolder "C:\scripts\Logs\" -DataStoreFilter "SAN_PROD" -TO "Shihan.Pietersz@pietersz.com.au" -FROM "Helpdesk@pietersz.com.au" -SMTPSERVER "mymailserver"
 
The Parameters are as outlined below
 
$VcenterServer – Vcenter server name
 
$Logfile Folder – the path where all log files to be stored in
Example, “C:\scripts\logs\” (with quotations)
 
$DataStoreFilter - The filter which datastore you would want to filter by.
Example, a datastore with a name PROD_SANxxx the parameter would be “PROD_SAN”. This will get all Vmware data stores that start with PROD_SAN
 
$TO – recipient email address
$FROM – Sender email address
$SMTPServer – SMTP Server address
$PasswordFileLocation - secure password file location
 
 
.NOTES
 
 
if the script needs to be run as a task. a secure user and password file needs to be genarated. follow the below process to genarate the file
$username = TestUser"
$password = "Password123!@#"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
Set-Content "C:\temp\Password.txt" $secureStringText
 
Point the $PasswordFileLocation to the password file.
 
.LINK
http://www.pietersz.com.au
  
 
#>


function Get-SRMEventInfo 
{
    param
    (
        [Parameter(Mandatory=$True,Position=1)]
        [String]$VcenterServer,
        [Parameter(Mandatory=$true,
                   Position=2,
                   ParameterSetName="ParameterSetName",
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   HelpMessage="Path to logfile one or more locations. ex c:\Logs\")]
        [string]$LogFileFolder,
        [parameter(Mandatory=$false,
                   Position=3,
                   HelpMessage="datastore to filter from ex: PRD_SAN")]
        [string]$DataStoreFilter,
        [System.Management.Automation.PSCredential]$Credential,
        [parameter(Mandatory=$false)]
        [string[]]$TO,
        [parameter(Mandatory=$false)]
        [string]$FROM,
        [parameter(Mandatory=$false)]
        [string]$SMTPSERVER

  
    )
       
    $HtmlHead = '<style>
                body {
                    background-color: white;
                    font-family: "Calibri";
                }
 
                table {
                    border-width: 1px;
                    border-style: solid;
                    border-color: black;
                    border-collapse: collapse;
                    width: 100%;
                }
 
                th {
                    border-width: 1px;
                    padding: 5px;
                    border-style: solid;
                    border-color: black;
                    color: #ffffff;
                    background-color: #f70404;
                }
 
                td {
                    border-width: 1px;
                    padding: 5px;
                    border-style: solid;
                    border-color: black;
                    background-color: White;
                }
 
                tr {
                    text-align: center;
                }
                </style>'

    Try
    {    
    
        if((Test-Path -Path "$LogFileFolder") -eq $false) { New-Item -ItemType Directory -Path $LogFileFolder }
        $Logfile = $LogFileFolder+(Get-Date -Format O |ForEach-Object {$_ -Replace ":", "."})+"SRMProtectionStatusReport.log"
        
        $CSVFile = $LogFileFolder+(Get-Date -Format O |ForEach-Object {$_ -Replace ":", "."})+"SRMProtectionStatusReport.csv"
        
        $ErrorCSVFile = $LogFileFolder+(Get-Date -Format O |ForEach-Object {$_ -Replace ":", "."})+"SRMProtectionErrorStatusReport.csv"
 
        $CurrentDate = (Get-date)
        Connect-VIServer -Server $VcenterServer -Credential $Credential 
        $srm = Connect-SrmServer -Credential $Credential
        $srmApi = $srm.ExtensionData
        $ProtectionGroups = $srmApi.Protection.ListProtectionGroups()

        $SrmErrorObjects = @()
        $SrmErrorObjects.Clear()
    
            foreach ($ProtectionGroup in $ProtectionGroups)
            { 
                
                $ProtectionGroupName = $ProtectionGroup.GetInfo().Name
                $ProtectionGroupCount = $ProtectionGroup.ListProtectedVms().Count
                add-content $logfile ""
                Add-Content $Logfile "SRM protection group $ProtectionGroupName Total of $ProtectionGroupCount VMs" 
                add-content $logfile ""
                Write-Output "SRM protection group" $ProtectionGroup.GetInfo().Name 
                
                    for ($v=0; $v -lt  $ProtectionGroup.ListProtectedVms().Count; $v++ )
                        {
                            
                            $vm = get-vm -ID $ProtectionGroup.ListProtectedVms()[$v].VM.MoRef
                            
                            $vmDatastore = Get-Datastore -VM $vm | Where-Object{$_.Name -like "*$DataStoreFilter*"} | Select-Object  Name, CapacityGB, @{Label="TotalSpaceUsed";Expression={"{0:n2}" -f ($_.CapacityGB-$_.FreeSpaceGB)}},  @{Label="FreeSpaceGB";Expression={"{0:n2}" -f ($_.FreeSpaceGB)}}
                            
                            $SrmVMInfo = $ProtectionGroup.QueryVmProtection(@($vm.ExtensionData.MoRef))
                            
                            $ConfigurationStatus = $SrmVMInfo.Status
                            
                                if($ConfigurationStatus -ne "IsProtected")
                                {
                                    
                                    $SrmErrorObjects += New-Object -TypeName psobject -Property @{VirtualMachine="$vm"; ConfigurationStatus="$ConfigurationStatus"}
                                    Add-Content $Logfile "$vm | Configuration Status $ConfigurationStatus"
                                    Write-Output "Configuration error on $vm | Status is $ConfigurationStatus"
                                    $ErrorProperties = [ordered]@{'Name' = $vm.Name
                                                                'State' = $vm.PowerState 
                                                                'Memory(GB)' = $vm.MemoryGB
                                                                'DataStore' = $vmDatastore.Name
                                                                'DataStoreCapacity(GB)' = $vmDatastore.CapacityGB
                                                                'DataStoreFreeSpace(GB)' = $vmDatastore.FreeSpaceGB
                                                                'OperatingSystem' = $vm.Guest   
                                                                'BackupFolder' = $vm.Folder
                                                                'ProtectionGroup' =  $ProtectionGroupName
                                                                'SRM Protection Status' = $ConfigurationStatus
                                                                'EsxiHost' = $vm.VMHost
                                                                  }
                                    $Errorobj = New-Object -TypeName psobject -Property $ErrorProperties
                                    $Errorobj | export-csv -Path $ErrorCSVFile -NoTypeInformation -Force -Append                
                                }
                                else 
                                {    
                                    Add-Content $Logfile "$vm | Configuration Status $ConfigurationStatus"
                                    Write-Output "VM Name $vm | Configuration Status $ConfigurationStatus" 
                                     $Properties = [ordered]@{'Name' = $vm.Name
                                                                'State' = $vm.PowerState 
                                                                'Memory(GB)' = $vm.MemoryGB
                                                                'DataStore' = $vmDatastore.Name
                                                                'DataStoreCapacity(GB)' = $vmDatastore.CapacityGB
                                                                'DataStoreFreeSpace(GB)' = $vmDatastore.FreeSpaceGB
                                                                'OperatingSystem' = $vm.Guest   
                                                                'BackupFolder' = $vm.Folder
                                                                'ProtectionGroup' =  $ProtectionGroupName
                                                                'SRM Protection Status' = $ConfigurationStatus
                                                                'EsxiHost' = $vm.VMHost
                                                                  }
                                    $obj = New-Object -TypeName psobject -Property $Properties
                                    $obj | export-csv -Path $CSVFile -NoTypeInformation -Force -Append




                                }                           
                        }

                        
            }

    } 
    
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        Send-MailMessage -to $To -From $FROM -SmtpServer $SMTPSERVER -Subject "Error in Get-SrmEvents script"  -Body "Get-SrmEvents script failed with error $ErrorMessage" -BodyAsHtml -Priority high
        Write-Output $ErrorMessage
    }
    Finally
    {
        if($SrmErrorObjects.Count -ne 0)
            {
            Clear-Host
            $Errorcount = $SrmErrorObjects.Count
            Write-Output ""
            Write-Output "SRM Protection issues detected on $Errorcount VMs please review !"
            $SrmErrorObjects | Format-Table -AutoSize
            $body = $SrmErrorObjects | Select-Object VirtualMachine, ConfigurationStatus |ConvertTo-Html -Head $HtmlHead -Property VirtualMachine, ConfigurationStatus -PreContent '<h3>SRM Protection Report</h3><br>' |Out-String
            Send-MailMessage -to $To -From $FROM -SmtpServer $SMTPSERVER -Subject "** Warning - SRM Protection Issues Detected" -BodyAsHtml "$body"  -Attachments "$ErrorCSVFile"
            Write-Output ""
            Write-Output ""
            Write-Output "SRM EventInfo script detected issues, sending email to $TO, Script completed on $CurrentDate" 
            Write-Output "logfile located in $Logfile"
            Add-Content $Logfile "SRM Configuration is Detected issues, sending email to $TO, Script completed on $CurrentDate"  

            }
        else
            {
                Write-Output ""
                Write-Output ""
                Write-Output "SRM Configuration is Healthy, Script completed on $CurrentDate" 
                Write-Output "logfile located in $Logfile"
                Add-Content $Logfile "SRM Configuration is Healthy, Script run on $CurrentDate" 
           
                           
            }
           
           
    }
}
#Get-SRMEventInfo -VcenterServer "VcenterServer" -LogFileFolder "C:\scripts\Logs\" -DataStoreFilter "SAN_PROD" -TO "to@testuser.com", -FROM "From@testuser.com" -SMTPSERVER "SMTPSERVER"