Get-VMSnapshot function (Part I)

I have created a function Get-VMSnapshot in PowerShell because I had the need to inform the customer of existing snapshots on there vSphere environment by integrating it in one function.

The Get-VMSnapshot function will give you the possibility to send the result to:

  • Email
  • Screen

In the near future I will adapt also the possibility to send the result to your Nagios monitoring.

Some requirements:

  • Create secure password file, when you would like to run the function as a schedule task.Create secure password file can be done as follow:
    "P@ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Pwd.txt"
  • Near future I will also give you the possibility to add an exclusion list of virtual machines.

Get-VMSnapshot

Function Get-VMSnapshot {
<#
.SYNOPSIS
   Connects to a vCenter environment and checks for snapshots in the vSphere environment, the result can be shown on your screen or send by email.
.DESCRIPTION
   The Get-VMSnapshot will connect to your vSphere environment and checks for snapshots in the vSphere environment, 
   the result can been shown on your screen or send via email. For more information about snapshots in the VMware environment, 
   check this link: https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1025279 
   This script has been tested on VMware vSphere ESXi 5.0.x | 5.1.x | 5.5.x | 6.0.x versions.
.EXAMPLE
   Get-VMSnapshot -Screen -vCenter  -UserName 
   Put the result of the found snapshots on the screen. Password of the user is NOT secured saved in a password file.
.EXAMPLE
   Get-VMSnapshot -Screen -vCenter  -UserName  -PwdFilePath C:\Pwd.txt
   Put the result of the found snapshots on the screen. Password of the user is secured saved in a password file.
.EXAMPLE
   Get-VMSnapshot -Email -vCenter  -UserName  -SMTPServer smtp.domain.com -FromAddress noreply@domain.Com -ToAddress email@domain.com -PwdFilePath C:\Pwd.txt
   The result of the found snapshots will be send via email. Password of the user is secured saved in a password file.
.EXAMPLE
   Get-VMSnapshot -Email -vCenter  -UserName  -SMTPServer smtp.domain.com -FromAddress noreply@domain.Com -ToAddress email@domain.com
   The result of the found snapshots will be send via email. Password of the user is NOT secured saved in a password file.
.NOTES
    Author: Frederik Bisback
    Created on: 10/06/2016
    Version: 1.0.0
.LINK
   http://blog.pronict.net
#>
        
        [CmdletBinding(DefaultParameterSetName="Screen")]
        param
            (
                [Parameter(Mandatory=$False,Position=0,HelpMessage="Show result on screen (Y/N)",ParameterSetName="Screen")][switch]$Screen = $True,
                [Parameter(Mandatory=$False,Position=0,HelpMessage="Send result by email (Y/N).",ParameterSetName="Email")][switch]$Email = $True,
                [Parameter(Mandatory=$True,Position=1)][alias("vCenter Server")][string]$vCenter,
                [Parameter(Mandatory=$True,Position=2)][string]$UserName,
                [Parameter(Mandatory=$False,Position=3)][alias("Password")][AllowNull()][string]$PwdFilePath,
                [parameter(Mandatory=$True, ParameterSetName="Email",HelpMessage="Enter the SMTP Server FQDN:")][String]$SMTPServer,
                [parameter(Mandatory=$True, ParameterSetName="Email",HelpMessage="Enter the FROM email address:")][String]$FromAddress,
                [parameter(Mandatory=$True, ParameterSetName="Email",HelpMessage="Enter the TO email address:")][String]$ToAddress
            )

    #Start 

    if($PSCmdlet.ParameterSetName -eq "Screen")
        {
            Write-Verbose -Message "The result will be shown onto the screen."
            $Error.Clear()
            #Start - Add VMware Snapin            
            Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
            if ($Error)
                {
                    Write-Host "ERROR - Please download and install the lastest vSphere PowerCLI software." -BackgroundColor Red -ForegroundColor White     
                    Write-Verbose "ERROR - Please download and install the lastest vSphere PowerCLI software."
                    Break
                }
            else 
                {
                    Write-Verbose "The snapin VMware.VimAutomation.Core has been succesfully added."
                }

            if(!$PwdFilePath)
                {
                    $vCenterCred = Get-Credential -UserName $UserName -Message "Logon to $vCenter ..."
                    Connect-VIServer -Server $vCenter -Credential $vCenterCred -ErrorAction SilentlyContinue

                    if($Error)
                        {
                            Write-Verbose "Connection could not been established with the vCenter server $vCenter. Check the command line for errors."
                            $Error.Clear()
                            Break
                        }
                    else 
                        {
                            Write-Verbose "Connection has been established with the vCenter server $vCenter."
                        }

                    #Start - Checking for Snapshots
                    Get-VM | Get-Snapshot | Format-table VM,Name,Description,Created
                    #End - Checking for Snapshots

                    #Start - Disconnect vCenter server session
                    Disconnect-VIServer -Server $vcenter -Confirm:$False -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Connection to the vCenter has not been closed!"
                        }
                    else
                        {
                            Write-Verbose "Connection to the vCenter has been closed."
                        }
                    #End - Disconnect vCenter server session  
                }
            else
                {                 
                    $vCenterCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, (Get-Content $PwdFilePath | ConvertTo-SecureString)
                    Connect-VIServer -Server $vCenter -Credential $vCenterCred -ErrorAction SilentlyContinue

                    if($Error)
                        {
                            Write-Verbose "Connection could not been established with the vCenter server $vCenter. Check the command line for errors."
                            $Error.Clear()
                            Break
                        }
                    else 
                        {
                            Write-Verbose "Connection has been established with the vCenter server $vCenter."
                        }

                    #Start - Checking for Snapshots
                    Get-VM | Get-Snapshot | Format-table VM,Name,Description,Created
                    #End - Checking for Snapshots
                    
                    #Start - Disconnect vCenter server session
                    Disconnect-VIServer -Server $vcenter -Confirm:$False -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Connection to the vCenter has not been closed!"
                        }
                    else
                        {
                            Write-Verbose "Connection to the vCenter has been closed."
                        }
                    #End - Disconnect vCenter server session         
                }
        }
    elseif($PSCmdlet.ParameterSetName -eq "Email")
        {
            Write-Verbose -Message "The result will be send by email."
            $Error.Clear()
            #Start - Add VMware Snapin            
            Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
            if ($Error)
                {
                    Write-Host "ERROR - Please download and install the lastest vSphere PowerCLI software." -BackgroundColor Red -ForegroundColor White     
                    Write-Verbose "ERROR - Please download and install the lastest vSphere PowerCLI software."
                    Break
                }
            else 
                {
                    Write-Verbose "The snapin VMware.VimAutomation.Core has been succesfully added."
                }

            if(!$PwdFilePath)
                {
                    $vCenterCred = Get-Credential -UserName $UserName -Message "Logon to $vCenter ..."
                    Connect-VIServer -Server $vCenter -Credential $vCenterCred -ErrorAction SilentlyContinue

                    if($Error)
                        {
                            Write-Verbose "Connection could not been established with the vCenter server $vCenter. Check the command line for errors."
                            $Error.Clear()
                            Break
                        }
                    else 
                        {
                            Write-Verbose "Connection has been established with the vCenter server $vCenter."
                        }
                    
                    $OutFile = $env:TEMP+"\snapshots.log"

                    #Start - Checking for Snapshots
                    Get-VM | Get-Snapshot | Format-table VM,Name,Description,Created | Out-File $OutFile
                    #End - Checking for Snapshots

                    #Start - Disconnect vCenter server session
                    Disconnect-VIServer -Server $vcenter -Confirm:$False -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Connection to the vCenter has not been closed!"
                            $Error.Clear()
                            Break
                        }
                    else
                        {
                            Write-Verbose "Connection to the vCenter has been closed."
                        }
                    #End - Disconnect vCenter server session  
                    
                    #Start - SendEmail
                    send-mailmessage -from $FromAddress -to $ToAddress -subject "GET-VMSnapshot" -body "Check the attachement" -Attachments $OutFile -priority High -smtpServer $SMTPServer -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Email has not been send! Please check you command line."
                            $Error.Clear()
                            Break
                        }
                    else
                        {
                            Write-Verbose "Email has been send."
                        }
                    #End - SendEmail
                    Remove-Item $OutFile -Recurse
                }
            else
                {                 
                    $vCenterCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, (Get-Content $PwdFilePath | ConvertTo-SecureString)
                    Connect-VIServer -Server $vCenter -Credential $vCenterCred -ErrorAction SilentlyContinue

                    if($Error)
                        {
                            Write-Verbose "Connection could not been established with the vCenter server $vCenter. Check the command line for errors."
                            $Error.Clear()
                            Break
                        }
                    else 
                        {
                            Write-Verbose "Connection has been established with the vCenter server $vCenter."
                        }
                    $OutFile = $env:TEMP+"\snapshots.log"

                    #Start - Checking for Snapshots
                    Get-VM | Get-Snapshot | Format-table VM,Name,Description,Created | Out-File $OutFile
                    #End - Checking for Snapshots
                    
                    #Start - Disconnect vCenter server session
                    Disconnect-VIServer -Server $vcenter -Confirm:$False -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Connection to the vCenter has not been closed!"
                        }
                    else
                        {
                            Write-Verbose "Connection to the vCenter has been closed."
                        }
                    #End - Disconnect vCenter server session 
                    
                    #Start - SendEmail
                    send-mailmessage -from $FromAddress -to $ToAddress -subject "GET-VMSnapshot" -body "Check the attachement" -Attachments $OutFile -priority High -smtpServer $SMTPServer -ErrorAction SilentlyContinue
                    if($Error)
                        {
                            Write-Verbose "Email has not been send! Please check you command line."
                            $Error.Clear()
                            Break
                        }
                    else
                        {
                            Write-Verbose "Email has been send."
                        }
                    #End - SendEmail
                    Remove-Item $OutFile -Recurse
                }

        }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s