Hyper-V-Backup.ps1

<#PSScriptInfo
 
.VERSION 20.07.13
 
.GUID c7fb05cc-1e20-4277-9986-523020060668
 
.AUTHOR Mike Galvin Contact: mike@gal.vin / twitter.com/mikegalvin_
 
.COMPANYNAME Mike Galvin
 
.COPYRIGHT (C) Mike Galvin. All rights reserved.
 
.TAGS Hyper-V Virtual Machines Full Backup Export Permissions Zip History
 
.LICENSEURI
 
.PROJECTURI https://gal.vin/2017/09/18/vm-backup-for-hyper-v
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
    .SYNOPSIS
    Hyper-V Backup Utility - Flexible backup of Hyper-V Virtual Machines.
 
    .DESCRIPTION
    This script will create a full backup of virtual machines, complete with configuration, snapshots/checkpoints, and VHD files.
    This script should be run on a Hyper-V host and the Hyper-V PowerShell management modules should be installed.
 
    To send a log file via e-mail using ssl and an SMTP password you must generate an encrypted password file.
    The password file is unique to both the user and machine.
    To create the password file run this command as the user and on the machine that will use the file:
 
    $creds = Get-Credential
    $creds.Password | ConvertFrom-SecureString | Set-Content c:\foo\ps-script-pwd.txt
 
    .PARAMETER BackupTo
    The path the virtual machines should be backed up to.
    Each VM will have its own folder inside this location.
    Do not add a trailing backslash.
 
    .PARAMETER List
    Enter the path to a txt file with a list of Hyper-V VM names to backup.
    If this option is not configured, all running VMs will be backed up.
 
    .PARAMETER Wd
    The path to the working directory to use for the backup before copying it to the final backup directory.
    Use a directory on local fast media to improve performance.
 
    .PARAMETER NoPerms
    Configures the utility to shut down the running VM(s) to do the file-copy based backup instead of using the Hyper-V export function.
    If no list is specified and multiple VMs are running, the process will run through the VMs alphabetically.
 
    .PARAMETER Keep
    Instructs the utility to keep a specified number of days’ worth of backups.
    VM backups older than the number of days specified will be deleted.
    Every effort has been taken to only remove backup files or folders generated by this utility.
 
    .PARAMETER Compress
    This option will create a zip file of each Hyper-V VM backup.
    Available disk space should be considered when using this option.
 
    .PARAMETER Sz
    Configure the utility to use 7-Zip to compress the VM backups.
    7-Zip must be installed in the default location ($env:ProgramFiles) if it is not found, Windows compression will be used as a fallback.
     
    .PARAMETER SzThreads
    Configure 7-Zip to use more threads. mmt1 [1 thread] - mmt8 [8 threads].
    Please note this switch is passed through to 7-Zip. See 7-Zip help for more information.
 
    .PARAMETER SzComp
    Configure 7-Zip's compression strength. mx1 [fast compression] - mx9 [ultra compression].
    Please note this switch is passed through to 7-Zip. See 7-Zip help for more information.
 
    .PARAMETER ShortDate
    Configure the script to use only the Year, Month and Day in backup filenames.
 
    .PARAMETER NoBanner
    Use this option to hide the ASCII art title in the console.
 
    .PARAMETER L
    The path to output the log file to.
    The file name will be Hyper-V-Backup_YYYY-MM-dd_HH-mm-ss.log.
    Do not add a trailing \ backslash.
 
    .PARAMETER Subject
    The subject line for the e-mail log. Encapsulate with single or double quotes.
    If no subject is specified, the default of "Hyper-V Backup Utility Log" will be used.
 
    .PARAMETER SendTo
    The e-mail address the log should be sent to.
 
    .PARAMETER From
    The e-mail address the log should be sent from.
 
    .PARAMETER Smtp
    The DNS name or IP address of the SMTP server.
 
    .PARAMETER User
    The user account to authenticate to the SMTP server.
 
    .PARAMETER Pwd
    The txt file containing the encrypted password for SMTP authentication.
 
    .PARAMETER UseSsl
    Configures the utility to connect to the SMTP server using SSL.
 
    .EXAMPLE
    Hyper-V-Backup.ps1 -BackupTo \\nas\vms -List C:\scripts\vms.txt -Wd E:\temp -NoPerms -Keep 30
    -Compress -Sz -SzThreads mmt8 -SzComp mx5 -L C:\scripts\logs -Subject 'Server: Hyper-V Backup' -SendTo me@contoso.com
    -From hyperv@contoso.com -Smtp smtp.outlook.com -User user -Pwd C:\foo\pwd.txt -UseSsl
 
    This will shutdown, one at a time, all the VMs listed in the file located in C:\scripts\vms.txt
    and back up their files to \\nas\vms, using E:\temp as a working directory. A zip file for each
    VM folder will be created using 7-zip. 7-zip will use 8 threads and medium compression. Any
    backups older than 30 days will also be deleted. The log file will be output to C:\scripts\logs
    and sent via e-mail with a custom subject line.
#>


## Set up command line switches.
[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("BackupTo")]
    $Backup,
    [alias("Keep")]
    $History,
    [alias("List")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $VmList,
    [alias("Wd")]
    $WorkDir,
    [alias("SzThreads")]
    $SzThreadNo,
    [alias("SzComp")]
    $SzCompL,
    [alias("L")]
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    $LogPath,
    [alias("Subject")]
    $MailSubject,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$NoPerms,
    [switch]$Compress,
    [switch]$Sz,
    [switch]$ShortDate,
    [switch]$NoBanner)

If ($NoBanner -eq $False)
{
    Write-Host ""
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " _ _ __ __ ____ _ _ _ _ _ _ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | \ \ / / | _ \ | | | | | | | (_) (_) | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | |__| |_ _ _ __ ___ _ _\ \ / / | |_) | __ _ ___| | ___ _ _ __ | | | | |_ _| |_| |_ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | __ | | | | '_ \ / _ \ '__\ \/ / | _ < / _ |/ __| |/ / | | | '_ \ | | | | __| | | | __| | | | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | |_| | |_) | __/ | \ / | |_) | (_| | (__| <| |_| | |_) | | |__| | |_| | | | |_| |_| | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |_| |_|\__, | .__/ \___|_| \/ |____/ \__,_|\___|_|\_\\__,_| .__/ \____/ \__|_|_|_|\__|\__, | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " __/ | | | | __/ | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |___/|_| Mike Galvin https://gal.vin |_| Version 20.07.13 |___/ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " "
    Write-Host ""
}

## If logging is configured, start logging.
## If the log file already exists, clear it.
If ($LogPath)
{
    $LogFile = ("Hyper-V-Backup_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date))
    $Log = "$LogPath\$LogFile"

    $LogT = Test-Path -Path $Log

    If ($LogT)
    {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log started"
}

## Function to get date in specific format.
Function Get-DateFormat
{
    Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}

Function Get-DateShort
{
    Get-Date -Format "yyyy-MM-dd"
}

Function Get-DateLong
{
    Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
}

## Function for logging.
Function Write-Log($Type, $Evt)
{
    If ($Type -eq "Info")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Evt"
        }

        Write-Host "$(Get-DateFormat) [INFO] $Evt"
    }

    If ($Type -eq "Succ")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Evt"
        }

        Write-Host -ForegroundColor Green "$(Get-DateFormat) [SUCCESS] $Evt"
    }

    If ($Type -eq "Err")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Evt"
        }

        Write-Host -ForegroundColor Red -BackgroundColor Black "$(Get-DateFormat) [ERROR] $Evt"
    }

    If ($Type -eq "Conf")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$Evt"
        }

        Write-Host -ForegroundColor Cyan -Object "$Evt"
    }
}

## Function for the options post backup.
Function OptionsRun
{
    ## If the -keep switch AND the -compress switch are NOT configured.
    If ($Null -eq $History -And $Compress -eq $False)
    {
        Write-Log -Type Info -Evt "Removing previous backups of $Vm"

        ## Remove all previous backup folders, including ones from previous versions of this script.
        If ($ShortDate)
        {
            Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*" -Directory | Remove-Item -Recurse -Force
        }

        else {
            Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force
        }

        ## If a working directory is configured by the user, remove all previous backup folders, including
        ## ones from previous versions of this script.
        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT)
            {
                If ($ShortDate)
                {
                    Get-ChildItem -Path $Backup -Filter "$Vm-*-*-*" -Directory | Remove-Item -Recurse -Force
                }

                else {
                    Get-ChildItem -Path $Backup -Filter "$Vm-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force
                }
            }
        }
    }

    ## If the -keep option IS configured AND the -compress option is NOT configured.
    else {
        If ($Compress -eq $False)
        {
            Write-Log -Type Info -Evt "Removing backup folders of $Vm older than: $History days"

            ## Remove previous backup folders older than the configured number of days, including
            ## ones from previous versions of this script.
            If ($ShortDate)
            {
                Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*" -Directory | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
            }

            else {
                Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
            }

            ## If a working directory is configured by the user, remove previous backup folders
            ## older than the configured number of days remove all previous backup folders,
            ## including ones from previous versions of this script.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupDirT = Test-Path $Backup

                If ($BackupDirT)
                {
                    If ($ShortDate)
                    {
                        Get-ChildItem -Path $Backup -Filter "$Vm-*-*-*" -Directory | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
                    }

                    else {
                        Get-ChildItem -Path $Backup -Filter "$Vm-*-*-***-*-*" -Directory | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
                    }
                }
            }
        }
    }

    ## Check to see if the -compress switch IS configured AND if the -keep switch is NOT configured.
    If ($Compress)
    {
        If ($Null -eq $History)
        {
            Write-Log -Type Info -Evt "Removing previous compressed backups"

            ## Remove all previous compressed backups, including ones from previous versions of this script.
            If ($ShortDate)
            {
                Remove-Item "$WorkDir\$Vm-*-*-*.zip" -Force
            }

            else {
                Remove-Item "$WorkDir\$Vm-*-*-***-*-*.zip" -Force
            }

            ## If a working directory is configured by the user, remove all previous compressed backups,
            ## including ones from previous versions of this script.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupFolderT = Test-Path $Backup

                If ($BackupFolderT)
                {
                    If ($ShortDate)
                    {
                        Remove-Item "$Backup\$Vm-*-*-*.zip" -Force
                    }

                    else {
                        Remove-Item "$Backup\$Vm-*-*-***-*-*.zip" -Force
                    }
                }
            }
        }

        ## If the -compress switch IS configured AND if the -keep switch IS configured.
        else {

            Write-Log -Type Info -Evt "Removing compressed backups of $Vm older than: $History days"

            ## Remove previous compressed backups older than the configured number of days, including
            ## ones from previous versions of this script.
            If ($ShortDate)
            {
                Get-ChildItem -Path "$WorkDir\$Vm-*-*-*.zip" | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Force
            }

            else {
                Get-ChildItem -Path "$WorkDir\$Vm-*-*-***-*-*.zip" | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Force
            }

            ## If a working directory is configured by the user, remove previous compressed backups older
            ## than the configured number of days, including ones from previous versions of this script.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupFolderT = Test-Path $Backup

                If ($BackupFolderT)
                {
                    If ($ShortDate)
                    {
                        Get-ChildItem -Path "$Backup\$Vm-*-*-*.zip" | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Force
                    }

                    else {
                        Get-ChildItem -Path "$Backup\$Vm-*-*-***-*-*.zip" | Where-Object CreationTime â€“lt (Get-Date).AddDays(-$History) | Remove-Item -Force
                    }
                }
            }
        }

        ## If the -compress switch and the -Sz switch IS configured, test for 7zip being installed.
        ## If it is, compress the backup folder, if it is not use Windows compression.
        If ($Sz -eq $True)
        {
            $7zT = Test-Path "$env:programfiles\7-Zip\7z.exe"
            If ($7zT -eq $True)
            {
                Write-Log -Type Info -Evt "Compressing $Vm backup using 7-Zip compression"

                If ($ShortDate)
                {
                    $ShortDateT = Test-Path -Path ("$WorkDir\$Vm-$(Get-DateShort).zip")

                    If ($ShortDateT)
                    {
                        Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                        $i = 1
                        $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                        $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                        If ($ShortDateExistT)
                        {
                            do {
                                $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                                $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                            } until ($ShortDateExistT -eq $false)
                        }

                        try {
                            & "$env:programfiles\7-Zip\7z.exe" -$SzThreadNo -$SzCompL -bso0 a -tzip ("$WorkDir\$ShortDateNN") "$WorkDir\$Vm\*"
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt $_
                        }
                    }

                    try {
                        & "$env:programfiles\7-Zip\7z.exe" -$SzThreadNo -$SzCompL -bso0 a -tzip ("$WorkDir\$Vm-$(Get-DateShort).zip") "$WorkDir\$Vm\*"
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }

                else {
                    try {
                        & "$env:programfiles\7-Zip\7z.exe" -$SzThreadNo -$SzCompL -bso0 a -tzip ("$WorkDir\$Vm-$(Get-DateLong).zip") "$WorkDir\$Vm\*"
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }
            }

            else {
                Write-Log -Type Info -Evt "Compressing $Vm backup using Windows compression"
                Add-Type -AssemblyName "system.io.compression.filesystem"
                If ($ShortDate)
                {
                    $ShortDateT = Test-Path -Path ("$WorkDir\$Vm-$(Get-DateShort).zip")

                    If ($ShortDateT)
                    {
                        Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                        $i = 1
                        $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                        $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                        If ($ShortDateExistT)
                        {
                            do {
                                $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                                $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                            } until ($ShortDateExistT -eq $false)
                        }

                        try {
                            [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$ShortDateNN"))
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt $_
                        }
                    }
                }

                else {
                    try {
                        [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$Vm-$(Get-DateLong).zip"))
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }
            }
        }

        ## If the -compress switch IS configured and the -Sz switch is NOT configured, compress
        ## the backup folder using Windows compression.
        else {

            Write-Log -Type Info -Evt "Compressing $Vm backup using Windows compression"
            Add-Type -AssemblyName "system.io.compression.filesystem"

            If ($ShortDate)
            {
                $ShortDateT = Test-Path -Path ("$WorkDir\$Vm-$(Get-DateShort).zip")

                If ($ShortDateT)
                {
                    Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                    $i = 1
                    $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                    $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                    If ($ShortDateExistT)
                    {
                        do {
                            $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                            $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                        } until ($ShortDateExistT -eq $false)
                    }

                    try {
                        [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$ShortDateNN"))
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }

                else {
                    try {
                        [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$Vm-$(Get-DateShort).zip"))
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }
            }

            else {
                try {
                    [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$Vm-$(Get-DateLong).zip"))
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }
        }

        ## Remove the VMs export folder.
        Get-ChildItem -Path $WorkDir -Filter "$Vm" -Directory | Remove-Item -Recurse -Force

        ## If a working directory has been configured by the user, move the compressed
        ## backup to the backup location and rename to include the date.
        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT -eq $False)
            {
                Write-Log -Type Info -Evt "Backup directory $Backup doesn't exist. Creating it."
                New-Item $Backup -ItemType Directory -Force | Out-Null
            }

            If ($ShortDate)
            {
                $ShortDateT = Test-Path -Path ("$Backup\$Vm-$(Get-DateShort).zip")

                If ($ShortDateT)
                {
                    Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                    $i = 1
                    $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN

                    If ($ShortDateExistT)
                    {
                        do {
                            $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                        } until ($ShortDateExistT -eq $false)
                    }

                    try {
                        Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*.zip" | Move-Item -Destination $Backup\$ShortDateNN
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }

                try {
                    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*.zip" | Move-Item -Destination $Backup
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }

            else {
                try {
                    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*-*-*.zip" | Move-Item -Destination $Backup
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }
        }
    }

    ## If the -compress switch is NOT configured AND if the -keep switch is configured, rename
    ## the export of each VM to include the date.
    else {
        If ($ShortDate)
        {
            $ShortDateT = Test-Path -Path ("$WorkDir\$Vm-$(Get-DateShort)")

            If ($ShortDateT)
            {
                Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                $i = 1
                $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}" -f $i++)
                $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                If ($ShortDateExistT)
                {
                    do {
                        $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}" -f $i++)
                        $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                    } until ($ShortDateExistT -eq $false)
                }

                try {
                    Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$ShortDateNN")
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }

            try {
                Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$Vm-$(Get-DateShort)")
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }
        }

        else {
            try {
                Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$Vm-$(Get-DateLong)")
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }
        }

        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT -eq $False)
            {
                Write-Log -Type Info -Evt "Backup directory $Backup doesn't exist. Creating it."
                New-Item $Backup -ItemType Directory -Force | Out-Null
            }

            If ($ShortDate)
            {
                $ShortDateT = Test-Path -Path ("$Backup\$Vm-$(Get-DateShort)")

                If ($ShortDateT)
                {
                    Write-Log -Type Info -Evt "File $Vm-$(Get-DateShort) already exists, appending number"
                    $i = 1
                    $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}" -f $i++)
                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN

                    If ($ShortDateExistT)
                    {
                        do {
                            $ShortDateNN = ("$Vm-$(Get-DateShort)-{0:D3}" -f $i++)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                        } until ($ShortDateExistT -eq $false)
                    }

                    try {
                        Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*" -Directory | Move-Item -Destination $Backup\$ShortDateNN -ErrorAction 'Stop'
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt $_
                    }
                }

                try {
                    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*" -Directory | Move-Item -Destination ("$Backup\$Vm-$(Get-DateShort)") -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }

            else {
                try {
                    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Move-Item -Destination ("$Backup\$Vm-$(Get-DateLong)") -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }
        }
    }
}

## Set a variable for computer name of the Hyper-V server.
$Vs = $Env:ComputerName

## If a VM list file is configured, get the content of the file.
## If a VM list file is not configured, just get the running VMs.
If ($VmList)
{
    $Vms = Get-Content $VmList
}

else {
    $Vms = Get-VM | Where-Object {$_.State -eq 'Running'} | Select-Object -ExpandProperty Name
}

## Check to see if there are any running VMs.
## If there are no VMs, then do nothing.
If ($Vms.count -ne 0)
{
    ## If the user has not configured the working directory, set it as the backup directory.
    If ($Null -eq $WorkDir)
    {
        $WorkDir = "$Backup"
    }

    If ($Null -eq $SzThreadNo)
    {
        $SzThreadNo = "mmt1"
    }

    If ($Null -eq $SzCompL)
    {
        $SzCompL = "mx1"
    }

    If ($Null -eq $ShortDate)
    {
        $ShortDate = "$LongDate"
    }

    ##
    ## Display the current config and log if configured.
    ##
    Write-Log -Type Conf -Evt "************ Running with the following config *************."
    Write-Log -Type Conf -Evt "This virtual host:.......$Vs."
    Write-Log -Type Conf -Evt "VMs to backup:..........."

    ForEach ($Vm in $Vms)
    {
        Write-Log -Type Conf -Evt ".........................$Vm"
    }

    Write-Log -Type Conf -Evt "Backup directory:........$Backup."
    Write-Log -Type Conf -Evt "Working directory:.......$WorkDir."
    
    If ($Null -ne $History)
    {
        Write-Log -Type Conf -Evt "Backups to keep:.........$History days"
    }

    else {
        Write-Log -Type Conf -Evt "Backups to keep:.........No Config"
    }

    If ($Null -ne $LogPath)
    {
        Write-Log -Type Conf -Evt "Logs directory:..........$LogPath."
    }
    
    else {
        Write-Log -Type Conf -Evt "Logs directory:..........No Config"
    }
    
    If ($MailTo)
    {
        Write-Log -Type Conf -Evt "E-mail log to:...........$MailTo."
    }
    
    else {
        Write-Log -Type Conf -Evt "E-mail log to:...........No Config"
    }
    
    If ($MailFrom)
    {
        Write-Log -Type Conf -Evt "E-mail log from:.........$MailFrom."
    }
    
    else {
        Write-Log -Type Conf -Evt "E-mail log from:.........No Config"
    }
    
    If ($MailSubject)
    {
        Write-Log -Type Conf -Evt "E-mail subject:..........$MailSubject."
    }

    else {
        Write-Log -Type Conf -Evt "E-mail subject:..........Default"
    }

    If ($SmtpServer)
    {
        Write-Log -Type Conf -Evt "SMTP server:.............$SmtpServer."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP server:.............No Config"
    }

    If ($SmtpUser)
    {
        Write-Log -Type Conf -Evt "SMTP user:...............$SmtpUser."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP user:...............No Config"
    }

    If ($SmtpPwd)
    {
        Write-Log -Type Conf -Evt "SMTP pwd file:...........$SmtpPwd."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP pwd file:...........No Config"
    }

    Write-Log -Type Conf -Evt "-UseSSL switch:..........$UseSsl."
    Write-Log -Type Conf -Evt "-NoPerms switch:.........$NoPerms."
    Write-Log -Type Conf -Evt "-ShortDate switch:.......$ShortDate."
    Write-Log -Type Conf -Evt "-Compress switch:........$Compress."
    Write-Log -Type Conf -Evt "-Sz switch:..............$Sz."
    Write-Log -Type Conf -Evt "7-zip threads:...........$SzThreadNo."
    Write-Log -Type Conf -Evt "7-zip compression:.......$SzCompL."
    Write-Log -Type Conf -Evt "************************************************************"
    Write-Log -Type Info -Evt "Process started."
    ##
    ## Display current config ends here.
    ##

    ##
    ## -NoPerms process starts here.
    ##

    ## If the -noperms switch is set, start a custom process to copy all the VM data.
    If ($NoPerms)
    {
        ForEach ($Vm in $Vms)
        {
            $VmInfo = Get-VM -name $Vm

            ## Test for the existence of a previous VM export. If it exists, delete it.
            $VmExportBackupT = Test-Path "$WorkDir\$Vm"
            If ($VmExportBackupT -eq $True)
            {
                Remove-Item "$WorkDir\$Vm" -Recurse -Force
            }

            ## Create directories for the VM export.
            try {
                New-Item "$WorkDir\$Vm" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\Virtual Machines" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\VHD" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\Snapshots" -ItemType Directory -Force | Out-Null
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }

            Write-Log -Type Info -Evt "Stopping VM: $Vm"
            Stop-VM $Vm

            ##
            ## Copy the VM config files and test for success or failure.
            ##

            try {
                Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id)" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force
                Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id).*" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }

            ##
            ## End of VM config files.
            ##

            ##
            ## Copy the VHDs and test for success or failure.
            ##

            try {
                Copy-Item $VmInfo.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }

            ##
            ## End of VHDs.
            ##

            ## Get the VM snapshots/checkpoints.
            $Snaps = Get-VMSnapshot $Vm

            ForEach ($Snap in $Snaps)
            {
                ##
                ## Copy the snapshot config files and test for success or failure.
                ##

                try {
                    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id)" "$WorkDir\$Vm\Snapshots\" -Recurse -Force
                    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id).*" "$WorkDir\$Vm\Snapshots\" -Recurse -Force
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }

                ##
                ## End of snapshot config.
                ##

                ## Copy the snapshot root VHD.
                try {
                    Copy-Item $Snap.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt $_
                }
            }

            Start-VM $Vm
            Write-Log -Type Info -Evt "Starting VM: $Vm"
            Start-Sleep -S 60
            OptionsRun
        }
    }

    ##
    ## -NoPerms process ends here.
    ##
    ##
    ## Standard export process starts here.
    ##

    ## If the -NoPerms switch is NOT set, for each VM check for the existence of a previous export.
    ## If it exists then delete it, otherwise the export will fail.
    else {
        ForEach ($Vm in $Vms)
        {
            $VmExportBackupT = Test-Path "$WorkDir\$Vm"
            If ($VmExportBackupT -eq $True)
            {
                Remove-Item "$WorkDir\$Vm" -Recurse -Force
            }

            If ($WorkDir -ne $Backup)
            {
                $VmExportWDT = Test-Path "$Backup\$Vm"
                If ($VmExportWDT -eq $True)
                {
                    Remove-Item "$Backup\$Vm" -Recurse -Force
                }
            }
        }

        ## Do a regular export of the VMs.
        ForEach ($Vm in $Vms)
        {
            Write-Log -Type Info -Evt "Attempting to export $Vm"
            try {
                $Vm | Export-VM -Path "$WorkDir" -ErrorAction 'Stop'
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt $_
            }
        }

        ## Run the configuration options on the above backup files and folders.
        ForEach ($Vm in $Vms)
        {
            OptionsRun
        }
    }
}

## If there are no VMs running, then do nothing.
else {
    Write-Log -Type Info -Evt "There are no VMs running to backup"
}

Write-Log -Type Info -Evt "Process finished."

## If logging is configured then finish the log file.
If ($LogPath)
{
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log finished"

    ## This whole block is for e-mail, if it is configured.
    If ($SmtpServer)
    {
        ## Default e-mail subject if none is configured.
        If ($Null -eq $MailSubject)
        {
            $MailSubject = "Hyper-V Backup Utility Log"
        }

        ## Setting the contents of the log to be the e-mail body.
        $MailBody = Get-Content -Path $Log | Out-String

        ## If an smtp password is configured, get the username and password together for authentication.
        ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL.
        If ($SmtpPwd)
        {
            $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
            $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

            ## If -ssl switch is used, send the email with SSL.
            ## If it isn't then don't use SSL, but still authenticate with the credentials.
            If ($UseSsl)
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
            }

            else {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
            }
        }

        else {
            Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
        }
    }
}

## End