Powershell function to create VMWare snapshots

For those who wants automate VMWare snapshots creation, I’ve prepared short Powershell function.
Script requires to have PowerCLI (available here https://my.vmware.com/web/vmware/details?downloadGroup=PCLI550&productId=352) installed on machine where it will be run.

function New-VMSnapshot{
       [CmdletBinding()]
        param
        (
            [Parameter(Position=0, Mandatory=$true, HelpMessage="vCenter server", ValueFromPipeline = $true)] $vCenter,
            [Parameter(Position=1, Mandatory=$true, HelpMessage="VM name", ValueFromPipeline = $true)] $VM,
            [Parameter(Position=2, Mandatory=$true, HelpMessage="Port", ValueFromPipeline = $true)] $Port,
            [Parameter(Position=3, Mandatory=$true, HelpMessage="Domain\Username", ValueFromPipeline = $true)] $User,
            [Parameter(Position=4, Mandatory=$true, HelpMessage="Password", ValueFromPipeline = $true)] $Password,
            [Parameter(Position=5, Mandatory=$false, HelpMessage="Snapshot description", ValueFromPipeline = $true)] $SnapshotDescription

        ) 

        Try
        {
            Add-PsSnapin VMware.VimAutomation.Core
        }
        Catch
        {
            return "Error: PowerCLI module not installed or can not be loaded." 
        }

        Try
        {
            $vCenterConnection = Connect-VIServer -Server $vCenter -Port $Port -User $User -Password $Password -WarningAction Ignore
            $Snapshot = "Snapshot " + (Get-Date -Format "dd-MM-yyyy hh:MM:ss")
            $NewSnapshot = New-Snapshot -VM $VM -Name $Snapshot -Description $SnapshotDescription
            If($NewSnapshot)
            {
                Return "Snapshot $Snapshot created."
            }
            else
            {
                Return "Error occured during snapshot creation."
            }
            Disconnect-VIServer $vCenterConnection -Confirm:$False
            Remove-PSSnapin VMware.VimAutomation.Core
        }
        Catch
        {
            return 'Error:' + $_.Exception.Message
        }
}

It’s not too long, but it works. Function can be used in situations when we need to create snapshots for big number of VMs.
I hope you will find this script useful and see you in the next article 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.