Search
StarWind is a hyperconverged (HCI) vendor with focus on Enterprise ROBO, SMB & Edge

PowerShell wizard script: Configure Hyper-V Replica in different scenarios (domain, workgroups, and mixed option)

  • December 26, 2024
  • 58 min read
Storage and Virtualization Engineer. Volodymyr has broad experience in solution architecture and data protection, backed by a technical background in applied physics.
Storage and Virtualization Engineer. Volodymyr has broad experience in solution architecture and data protection, backed by a technical background in applied physics.

INTRODUCTION

As an admin, I’m fully aware that while working with the virtual infrastructures, plan A doesn’t always relay a guarantee, so you have to have plan B up your sleeve. Microsoft Hyper-V Replica inbuilt technology is a massive help in a lot of cases. If you want to find out more about why exactly this technology is a life-saver in the matters of Hyper-V disaster recovery, look it up here.

Since one way or another, you have to add and configure new Hyper-V hosts or to improve already existing ones, no wonder I came upon a set of the same actions, that are quite simple in use and not complicated at all, of course, if we’re talking hosts in the domain. However, what one supposed to do if one doesn’t have a domain? Or if your goal is a mixed replication between a host and a domain, or vice versa? Recently I faced a task just like that. After a long time spent on researching how it works and finding a working algorithm, I realized that there are no existing means of automating this process. So, I had to develop a one myself. As a result, long hours of tiresome, albeit productive work, brought me this quite large yet very efficient script that I have decided to share with you!

Bear Grylls

So, first things first. The journey started with these two articles. My highest regards to the authors: your work hasn’t been in vain. For the same reason, I won’t dedicate too much time to describe the process itself in all preciseness, just take my time explaining the most critical stages of the script.

DO keep in mind, however, that this script is designed for replication between the hosts with the same OS version! If you try and apply it for the hosts that have different OS versions, don’t blame me for damaging your infrastructure. The script was tested on Windows Server 2019 and Windows Server 2016. I can’t deny that it might work on Windows Server 2012 R2 as well, but if you must, do it at your own risk, since it wasn’t tested for this version.

HOW IT WORKS

Replication scenarios:

Replicated host\host with replica Hyper-V domain member Hyper-V workgroup member
Hyper-V domain member + +
Hyper-V workgroup member + +

As we can see from the sheet, the script will help to configure all the possible hosts’ combination for the replication. Although a mixed combination of the domain hosts with the hosts outside the domain is supposedly possible, I would rather avoid that if I were you, so that there won’t be any problems in the future. The only problem with these scenarios (except for replication inside the domain) is that you’ll have to perform a series of additional steps, such as authentication between the hosts based on certificates and several other configuration settings. However, the script still takes it all into account, so don’t worry.

This script works perfectly with the hosts not engaged in replication processes before. If we are talking hosts that already have existing replication configuration, I’m afraid you’ll have to disable it. The script won’t be performing if even one of the hosts involved has active replication configuration, and the VMs with such configurations won’t be available to you unless you disable these settings manually. I did it on purpose to avoid a chance of disrupting an already working scheme. The script is equipped with numerous testing tools to deal with possible errors, and I just hope you won’t be needing them.

What does it do?

Preserving the current value of Trustedhosts variable on the host where the script is running or on the remote host should you decide to run this script remotely, so that you could return the previous value of the variable once the work is done.

Verifying of the IP addresses and their credentials for correctness.

Verifying of the necessity to create self-signed certificates and to apply additional settings.

If necessary, creating and adding self-signed certificates to the hosts (these certificates remain valid for two years); performing all required actions in the registry, firewall rules, and hosts files of both configured hosts.

Turning on and configuring replication on both hosts using Kerberos (for replication inside the domain) or certificates (for everything else).

Enabling the selection of one VM or defining all VMs available for replication to start the processes of replication and configuration, providing a possibility to exit the script if necessary.

PIECE OF ADVICE

To start it up, you’ll need to copy the text of the script, save it locally with the name «VM_Replication.ps1» on one of the hosts or a PC that has network access to the both of them. Run it with PowerShell as Administrator.

Run as Administrator

What you need as well are credentials and IP addresses of local or domain admins from both hosts. You need to run the script as an admin; otherwise, you simply won’t have enough rights to run commands correctly.

Start the script and follow the commentaries to enter the information required for the replication process to begin (hostnames, usernames, their credentials).

Start the script

In my specific case, the replication was configured between two hosts in the workgroup «Work». Make sure there are no errors in configuration stages: you’ll have no hard time finding errors since they will be highlighted with red if they should occur.

Select the required scenario. It can be all the VMs with disabled replication, in case you need a remote copy of this host.

Select the required scenario

Make sure the script is finished successfully!

Also, while selecting a specific scenario, you can go with replicating one of the VM from the list of the VMs available for replication. This is more of a testing option. Replication for the rest of the VMs you can configure later with GUI or PowerShell.

Make sure the script is finished successfully

If you ever enter the wrong information, you’ll be notified of this immediately and will be able to try again. These are several examples of notifications you may receive:

Examples of notifications

The script also takes care of even more serious errors, such as previously configured replication or multiple command errors. Take a look at this one, for example:

Multiple command errors

Keep in mind that after the work is done, you won’t be able just to restart the script and start over. For the next replication, you would need to clear everything and disable the existing configuration!

<#
.SYNOPSIS A wizard script for initial configuration and turning on VM replication between Hyper-V hosts.
.EXAMPLE PS> .\VM_Replication.ps1
#>
  
## Assigning values to variables.
$MyPath = Split-Path $MyInvocation.MyCommand.Path
$ExpDate = (Get-Date).AddYears(2).ToString("MM-dd-yyyy HH:MM:ss")
$SourceHCert = $null
$ReplicaHCert = $null
$SwitchInputH = $null
$FnSwitch = $null
$IsDomainHost = $null
$HostNum = $null
#requires –RunAsAdministrator
## Zeroing ErrorVariable.
$Error.Clear()
  
## Script exit() function.
function ExitPS
  {
        ## Verifying the necessity to remove temporary certificates.
        if ($SriptHName -ne $SourceHName -and $SriptHName -ne $ReplicaHName)
            {
                ## Removing temporary certificates.
                (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *"CN=Hyper-V Replica Root CA") | Remove-Item -Force -ErrorAction Continue
                (Get-ChildItem Cert:\LocalMachine\CA | Where -Prop Subject -like *"CN=Hyper-V Replica Root CA") | Remove-Item -Force -ErrorAction Continue
                (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$SourceHName) | Remove-Item -Force -ErrorAction Continue
                (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$ReplicaHName) | Remove-Item -Force -ErrorAction Continue
                    }  
                        else
                            {
                                ## Verifying the necessity to remove temporary certificates.
                                if ($SriptHName -eq $SourceHName)
                                    {
                                        ## Removing temporary certificates.
                                        (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *"CN=Hyper-V Replica Root CA") | Remove-Item -Force -ErrorAction Continue
                                        (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$ReplicaHName) | Remove-Item -Force -ErrorAction Continue
                                            }
                                               else
                                                    {
                                                        ## Removing temporary certificates.                               
                                                        (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *"CN=Hyper-V Replica Root CA") | Remove-Item -Force -ErrorAction Continue
                                                        (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$SourceHName) | Remove-Item -Force -ErrorAction Continue
                                                            }
                                    }
    ## Removing Powershell sessions.
    Get-PSSession | Remove-PSSession -Confirm:$false
    ## Verifying the necessity to restore Trustedhosts value.
    if ($CurTH -ne $null)
        {
            ## Resoting previous Trustedhosts values.
            Set-Item wsman:\localhost\Client\Trustedhosts $CurTH –Force -ErrorAction Stop
                }
    ## Checking the message flag.
    if ($Flag -eq 'Exit')
        {
            ## Message output.
            Write-Host "The script execution is completed successfully!" -ForegroundColor Green
                }
                   else
                         {
                            ## Message output.
                            Write-Host "The script execution has failed!" -ForegroundColor Red
                                }
    ## Removing variables.
    Remove-Variable -Name * -Force -ErrorAction SilentlyContinue | Out-Null
    ## Pause
    pause
    ## Clearing the screen.
    Clear-Host
    ## Exiting PowerShell.
    exit
        }
  
## Function for temporary access rights to any configurable hosts in Trustedhosts of the current PC.
function SetNewSettings
    {
        ## Assigning values to variables.
        $CurTH = (get-item wsman:\localhost\Client\TrustedHosts -Force ).value
        $NewTH = '*'
        ## Zeroing ErrorVariable.
        $Error.Clear()
        ## Exception handling.
        try
            {
               ## Setting new parameters in Trustedhosts.
               Set-Item wsman:\localhost\Client\Trustedhosts "$NewTH" –Force -ErrorAction Continue
               ## Checking for errors.
               if ($Error[0].Exception.Message -eq $null)
                    {
                        ## Message output.
                        Write-Host "Temporary access rights to any configurable hosts for the script execution have been added to Trustedhosts of the current machine!"  -ForegroundColor Green
                            }
                                else
                                    {
                                        ## Generating error.
                                        throw "Temporary access rights to any configurable hosts for the script execution have not been added to Trustedhosts of the current machine!"
                                        ## Calling script exit function.
                                        FunctionSwitching ($FnSwitch = '11')
                                            } 
                 }
                    catch
                            {
                                ## Checking for errors.
                                if ($Error[0].Exception.Message -ne $null)
                                    {
                                       ## Generating error.
                                       throw  "Configurable hosts data has not been added to Trustedhosts of the current machine!"
                                       ## Calling script exit function.
                                       FunctionSwitching ($FnSwitch = '11')
                                           }
                                       }
       ## Calling next function.
       FunctionSwitching ($FnSwitch = '1')
        }
  
## Input host availability check function.
function CheckInputH
    {
        ## Verifying the first stage of entering the host address.
        if ($SwitchInputH -eq $null -and $FnSwitch -ne '2')
            {
                ## Accepting user parameters.
                $SourceH = Read-Host "Enter the IP address of the replicated host"
                ## Verifying the IP address availability.
                if ($SourceH -notlike $null -and (Test-Connection -computer $SourceH -Quiet -ErrorAction SilentlyContinue) -eq $True)
                    {
                        ## Exception handling.
                        try
                            {
                                ## Assigning values to variables.
                                $User = Read-Host "Enter Username for the $SourceH"
                                $Password = Read-Host "Enter Password for the $SourceH" -AsSecureString
                                $SourceHCredential = New-Object System.Management.Automation.PSCredential -ArgumentList ($User,$Password)
                                ## Executing settings on a remote host.
                                $SourceHName =  Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ErrorAction Stop -ScriptBlock {
                                                                                                                                                       ## Getting DNS host name.
                                                                                                                                                       [System.Net.Dns]::GetHostbyName("localhost").HostName
                                                                                                                                                          }
                                    }
                                      catch
                                            {
                                                ## Checking for errors.
                                                if ($Error[0].Exception.Message -ne $null)
                                                    {
                                                      ## Messages output.
                                                      Write-Host "Incorrect username or password to $SourceH host!"  -ForegroundColor red
                                                      ## Zeroing ErrorVariable.
                                                      $Error.Clear()
                                                      ## Calling a function.
                                                      FunctionSwitching ($FnSwitch = '1')
                                                               }
                                                    }
                        ## Message output.
                        Write-Host "$SourceH host is written and avaliable!" -ForegroundColor Green
                        ## Assigning value to variable.
                        $CurrentHost = $SourceH
                        ## Calling a function.
                        FunctionSwitching ($FnSwitch = '2')                 
                                }
                                    Else
                                            {
                                                ## Message output.
                                                Write-Host "$SourceH host is not available, incorrect IP address, or File and Printer Sharing (Echo Request - ICMPv4-In) firewall rule is disabled on $SourceH host!" -ForegroundColor Red
                                                ## Calling a function.
                                                FunctionSwitching ($FnSwitch = '1')
                                                    }
                        }
                            ## Verifying the 2 stage of entering host address.
                            elseif($FnSwitch -ne '2')
                                    {
                                         ## Getting parameters from the user.
                                         $ReplicaH = Read-Host "Enter IP address of the host with replica"                                         
                                         ## Verifying the entered addresses.
                                         If ($SourceH -eq $ReplicaH)
                                             {
                                                  ## Message output.
                                                  Write-Host "The addresses of the replicated host and the host with replica must differ!" -ForegroundColor Red
                                                  ## 2 seconds' delay before calling a function.
                                                  sleep 2
                                                  ## Zeroing ErrorVariable.
                                                  $Error.Clear()
                                                  ## Calling a function.
                                                  FunctionSwitching ($FnSwitch = '1')
                                                         }
                                                           else
                                                                 {
                                                                   ## Verifying if the entered address is available.
                                                                   if ($ReplicaH -notlike $null -and (Test-Connection -computer $ReplicaH -Quiet -ErrorAction SilentlyContinue) -eq $True)
                                                                         {
                                                                            ## Exception handling.
                                                                            try
                                                                                {
                                                                                    ## Assigning value to variable.
                                                                                    $User = Read-Host "Enter Username for the $ReplicaH"
                                                                                    $Password = Read-Host "Enter Password for the $ReplicaH" -AsSecureString
                                                                                    $ReplicaHCredential = New-Object System.Management.Automation.PSCredential -ArgumentList ($User,$Password)
                                                                                    ## Executing settings on a remote host.
                                                                                    $ReplicaHName =  Invoke-Command -ComputerName $ReplicaH -Credential $ReplicaHCredential -ErrorAction Stop -ScriptBlock {
                                                                                                                                                                                                                ## Getting DNS host name.
                                                                                                                                                                                                                [System.Net.Dns]::GetHostbyName("localhost").HostName
                                                                                                                                                                                                                    }
                                                                                        }
                                                                                            catch
                                                                                                    {
                                                                                                        ## Checking for errors.
                                                                                                        if ($Error[0].Exception.Message -ne $null)
                                                                                                            {
                                                                                                                ## Messages output.
                                                                                                                Write-Host "Incorrect username or password to $ReplicaH host!"  -ForegroundColor red
                                                                                                                ## Calling script exit function.
                                                                                                                FunctionSwitching ($FnSwitch = '1')
                                                                                                                    }
                                                                                                                }
                                                    ## Message output.
                                                    Write-Host "$ReplicaH host is written and avaliable!" -ForegroundColor Green
                                                    ## Assigning value to variable.
                                                    $CurrentHost = $ReplicaH
                                                    ## Calling a function.
                                                    FunctionSwitching ($FnSwitch = '2')
                                                        }
                                                            Else
                                                                   {
                                                                        ## Message output.
                                                                        Write-Host "$ReplicaH host is not available, incorrect IP address or File and Printer Sharing (Echo Request - ICMPv4-In) rule is disabled on $ReplicaH host!" -ForegroundColor Red
                                                                        ## Calling a function.
                                                                        FunctionSwitching ($FnSwitch = '1')
                                                                            }
                                                                     }
                                                }
                       }
## Host selection confirmation function.
function ConfirmHSelection
    {
       ## Getting parameters from the user.
       $HChoice = read-host "Attention! The host address has been entered: $CurrentHost! Do you want to continue configuring this host? (y/n)"
       ## Switching function mode.
       Switch($HChoice)
            {
              Y{
                   ## Verifying a stage of entering host address.
                   If ($SwitchInputH -eq $null)
                        {
                             ## Assigning values to variables.
                             $SwitchInputH = '1'
                             $HChoice = $null
                                }
                                     else
                                           {
                                               ## Calling next function.
                                               FunctionSwitching ($FnSwitch = '3')
                                                 }
                    ## Calling a function.
                    FunctionSwitching ($FnSwitch = '1')
                        }
              N{
                   ## Calling a function.
                   FunctionSwitching ($FnSwitch = '1')
                       }
  
        default{
                    ## Message output.
                    write-host "You have entered an invalid value! Please, try again!" -foregroundcolor red
                    ## 2 seconds' delay before calling a function.
                    sleep 2
                    ## Calling a function.
                    FunctionSwitching ($FnSwitch = '2')
                        }
                  }
         }
  
## Hosts configuration function.
function ConfigureHosts
    {
        ## Switching function mode.
        Switch($HostNum)
                    {
                         $null{
                                  ## Assigning values to variables.                                
                                  $HCredential = $SourceHCredential
                                  $H = $SourceH
                                  $HName = $SourceHName
                                  $HostNum = '1'
                                    }
                            1 {
                                  ## Assigning values to variables.
                                  $HCredential = $ReplicaHCredential
                                  $H = $ReplicaH
                                  $HName =$ReplicaHName
                                  $HostNum = '2'
                                    }
                      default {
                                  ## Message output.
                                  write-host "Fatal error encountered during the script execution! Reboot and continue the script!" -ForegroundColor Red
                                  ## Calling script exit function.
                                  FunctionSwitching ($FnSwitch = '11')
                                            }
                                }
        ## Verifying function execution mode.
        if ($HostNum -le '2')
            {
        ## Verifying host availability.
        if ((Get-WindowsFeature -Name 'Hyper-V' -ComputerName $H -Credential $HCredential -ErrorAction Stop -ErrorVariable Erorr).InstallState -eq 'Installed')
            {
                 ## Message output.
                 Write-Host "Hyper-V service on $H ($HName) host is available and working normally!" -ForegroundColor Green
                 ## Executing settings on a remote host.
                 $IsDomainHost = Invoke-Command -ComputerName $H -Credential $HCredential -ErrorAction Stop -ScriptBlock{
                                ## Exception handling.
                                try
                                    {
                                        ## Enabling the firewall rules necessary for replication.
                                        Enable-NetFirewallRule -displayname "Hyper-V Replica HTTP*” -ErrorAction Stop -ErrorVariable Erorr
                                        ## Checking for errors.
                                        if ($Error[0].Exception.Message -eq $null)
                                             {
                                                ## Message output.
                                                Write-Host "The necessary rules on $Using:HName host firewall are enabled!"  -ForegroundColor Green
                                                                    }
                                        ## Verifying the domain / workgroup presence.
                                        if ((Get-WmiObject -Class Win32_ComputerSystem).Workgroup -ne $null)
                                             {
                                        ## Checking for errors.
                                        if ($Error[0].Exception.Message -eq $null)
                                             {
                                                ## Message output.
                                                Write-Host "$Using:HName host is a "(Get-WmiObject -Class Win32_ComputerSystem).Workgroup" workgroup member, to set a trust relationship between the hosts, self-signed certificates will be created and applied!" -ForegroundColor Green
                                                    }
                                        ## Setting host configuration parameter.
                                        if ($Using:IsDomainHost -eq $null)
                                            {
                                                ## Assigning value to variable.
                                                $IsDomainHost = 1
                                                    }
                                                        else
                                                            {
                                                                 ## Assigning value to variable.
                                                                 $IsDomainHost = 2
                                                                    }
                                              }
                                                else
                                                    {
                                                        ## Verifying the further host configuration mode.
                                                        if($Using:IsDomainHost -notlike $null )
                                                            {
                                                                ## Checking for errors.
                                                                if ($Error[0].Exception.Message -eq $null)
                                                                     {
                                                                         ## Message output.
                                                                         Write-Host "$Using:HName host is a"(Get-WmiObject -Class Win32_ComputerSystem).Domain"domain member, to set a trust relationship between the hosts, self-signed certificates will be created and applied!" -ForegroundColor Green
                                                                                }
                                                                         ## Assigning value to variable.
                                                                         $IsDomainHost = 2
                                                                                }
                                                                                   else
                                                                                        {
                                                                                            ## Checking for errors.
                                                                                            if ($Error[0].Exception.Message -eq $null)
                                                                                                {
                                                                                                    ## Message output.
                                                                                                     Write-Host "$Using:HName is a"(Get-WmiObject -Class Win32_ComputerSystem).Domain"domain member!" -ForegroundColor Green
                                                                                                        }
                                                                                                 }
                                                                }
                                                             }
                                                                catch
                                                                        {
                                                                            ## Checking for errors.
                                                                            if ($Error[0].Exception.Message -ne $null)
                                                                                {
                                                                                    ## Messages output.
                                                                                    Write-Host "$Using:HName host configuration is not finished due to errors!"  -ForegroundColor red
                                                                                    ## Calling script exit function.
                                                                                    FunctionSwitching ($FnSwitch = '11')
                                                                                            }
                                                                                }
                                                              ## Returning the variable value to the current session..
                                                              return($IsDomainHost)
                                                                }  -ErrorVariable Erorr
                                            }
                                               else
                                                     {
                                                         ## Message output.
                                                         Write-Host "Hyper-V service on $H ($HName) host is not installed, is not working, or is not available! Install (start) the service, then run the script again!" -ForegroundColor Red
                                                         ## Calling script exit function.
                                                         FunctionSwitching ($FnSwitch = '11')                             
                                                             }
        ## Checking for errors.
        if ($Error[0].Exception.Message -eq $null)        
                {
                    ## Message output.
                    Write-Host "Verifying $HName host configuration is successfully finished!" -ForegroundColor Green
                    ## Verifying the condition of calling the next functions.
                    if ($HostNum -eq '2')
                       {
                       if ($IsDomainHost -eq $null){
                        ## Calling next function.
                        FunctionSwitching ($FnSwitch = '7')
                            }
                              else
                                    {
                                       ## Calling next function.
                                       FunctionSwitching ($FnSwitch = '4')
                                         }
                                   }
                                        else
                                                {
                                                     ## Calling a function again.
                                                     FunctionSwitching ($FnSwitch = '3')
                                                        }
                         }
                            else                
                                   {
                                      ## Message output.
                                      Write-Host "$HName host configuration cannot be finished!" -ForegroundColor Red
                                      ## Calling script exit function.
                                      FunctionSwitching ($FnSwitch = '11')
                                         }
                            }
               }
  
## Function of adding information about hosts to hosts file.
function AddtoEtcHosts
    {
     ## Switching function mode.
     Switch($EtcCount)
                    {
                       $null {
                                 ## Assigning values to variables.
                                 $H = $SourceH
                                 $H2 = $ReplicaH
                                 $HName = $SourceHName
                                 $HName2 = $ReplicaHName
                                 $HCredential = $SourceHCredential
                                 $EtcCount = 1
                                    }
                            1 {
                                 ## Assigning values to variables.
                                 $H = $ReplicaH
                                 $H2 = $SourceH
                                 $HName = $ReplicaHName
                                 $HName2 = $SourceHName
                                 $HCredential = $ReplicaHCredential
                                 $EtcCount = 2
                                    }
                      default {
                                 ## Message output.
                                 write-host "Fatal error encountered during the script execution! Reboot and continue the script!" -ForegroundColor Red
                                 ## Calling script exit function.
                                 FunctionSwitching ($FnSwitch = '11')
                                    }
                          }
    ## Verifying function execution mode.
    if ($EtcCount -le 2)
        {
           ## Exception handling.
           try
               {
                 ## Invoking commands on the remote host via remote PowerShell session.
                 $File = Invoke-Command -ComputerName $H -Credential $HCredential  -ErrorAction Stop -ScriptBlock{
                 ## Assigning value to variable.
                 $File = "$env:windir\System32\drivers\etc\hosts"
                 ## Assigning value to variable.
                 $Hosts =  Select-String -Path $File -Pattern $Using:H -SimpleMatch -ErrorAction Stop
                 ## Verifying the necessity of adding information about hosts to hosts file.         
                 if ($Hosts -eq $null)
                     {
                        ## Exception handling.
                        try
                             {
                               ## Adding information about hosts to hosts file.
                               ""| Add-Content -PassThru $File -ErrorAction Stop| Out-Null
                               $Using:H+" "+$Using:HName | Add-Content -PassThru $File -ErrorAction Stop | Out-Null
                                  }
                                     catch
                                           {
                                             ## Checking for errors.
                                             if ($Error[0].Exception.Message -ne $null -or $File -eq $null)
                                                 {
                                                     ## Message output.
                                                     write-error $error[0].Exception.Message
                                                                 }
                                                          }
                                                     }
               ## Assigning value to variable.
               $Hosts =  Select-String -Path $File -Pattern $Using:H2 -SimpleMatch -ErrorAction Stop
               ## Verifying the necessity of adding information about hosts to hosts file.         
               if ($Hosts -eq $null)
                           {
                              ## Exception handling.
                              try
                                  {
                                    ## Adding information about hosts to hosts file.
                                    ""| Add-Content -PassThru $File -ErrorAction Stop| Out-Null
                                    $Using:H2+" "+$Using:HName2 | Add-Content -PassThru $File -ErrorAction Stop | Out-Null
                                        }
                                            catch
                                                    {
                                                      ## Checking for errors.
                                                      if ($Error[0].Exception.Message -ne $null -or $File -eq $null)
                                                            {
                                                                ## Message output.
                                                                write-error $error[0].Exception.Message
                                                                    }
                                                          }
                                      }
              ## Returning the variable value.
              return($File)                                       
                                         }
                                  }
                                    catch
                                          {
                                              ## Checking for errors.
                                              if ($Error[0].Exception.Message -ne $null -or $File -eq $null)
                                                 {
                                                     ## Message output.
                                                     write-error $error[0].Exception.Message
                                                        }
                                                          }  
                }
 ## Checking for errors.
 if ($Error[0].Exception.Message -eq $null -and $File -ne $null)
      {
         ## Message output.
         Write-Host "Information about hosts ($HName and $HName2) has been added to the file $File on $HName host!" -ForegroundColor Green
             }
                else
                     {  ## Message output.
                        Write-Host "Error adding information about the hosts ($HName and $HName2) to the file $File on $HName!" -ForegroundColor Red
                        ## Calling script exit function.
                        FunctionSwitching ($FnSwitch = '11')
                                              }
## Verifying the function calling condition.
if($EtcCount -eq 2)
    {
        ## Calling next function.
        FunctionSwitching ( $FnSwitch = '5')
            }
                else
                        {
                             ## Calling a function again.
                             FunctionSwitching ($FnSwitch = '4') 
                                }
             }
  
## Function of creating a root certificate on the local machine.
function CreateRootCert
    {
        ## Assigning value to variable.
        $RootCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq "CN=Hyper-V Replica Root CA" )
        ## Verifying the necessity of creating a root certificate.
        if ($RootCert -eq $null)
            {
                ## Exception handling.
                try
                    {
                        ## Creating a root certificate.
                        New-SelfSignedCertificate -DnsName "Hyper-V Replica Root CA" -CertStoreLocation Cert:\LocalMachine\My -KeyLength 4096 -Hash SHA256 -KeyFriendlyName "Hyper-V Replica Root CA" -FriendlyName "Hyper-V Replica Root CA" -NotBefore "2020-01-01 01:00:00" -NotAfter $ExpDate -KeyUsage CertSign,CRLSign,DigitalSignature -ErrorAction Stop | Out-Null
                        ## Assigning value to variable.
                        $RootCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq "CN=Hyper-V Replica Root CA" )
                        ## Assigning value to variable.
                        $RCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq "CN=Hyper-V Replica Root CA" ).FriendlyName
                            }
                               catch
                                     {
                                        ## Message output.
                                        Write-Host $error[0].Exception.Message
                                            }
                                            finally
                                                    {
                                                        ## Checking for errors.
                                                        if ($Error[0].Exception.Message -eq $null)
                                                            {
                                                                ## Message output.
                                                                Write-Host "A root certificate $RCert is successfully created!" -ForegroundColor Green
                                                                ## Calling next function.
                                                                FunctionSwitching ($FnSwitch = '6')
                                                                      }
                                                                         else
                                                                                {
                                                                                    ## Message output.
                                                                                    Write-Host "Error creating a root certificate!" -ForegroundColor Red
                                                                                    ## Calling script exit function.
                                                                                    FunctionSwitching ($FnSwitch = '11')
                                                                                        }
                                                            }
            }
                else
                        {
                            ## Message output.
                            Write-Host "Attention! A root certificate created upon the previous running of the script will be used!" -ForegroundColor Yellow
                            ## Calling next function.
                            FunctionSwitching ($FnSwitch = '6')                             
                                }
             }
  
## Function of adding the certificate to the Hyper-V host and additional configuration.
function AddCerttoHost
    {
      ## Assigning value to variable.
      $RootCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq "CN=Hyper-V Replica Root CA" )
      ## Switching function mode.
      Switch($CertCount)
                    {
                       $null {
                                 ## Assigning values to variables.
                                 $HCertName = "CN="+$SourceHName
                                 $HCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq $HCertName )
                                 $HName = $SourceHName
                                 $H = $SourceH
                                 $HCredential = $SourceHCredential
                                 $SourceHPSS = New-PSSession -ComputerName $SourceH -Credential $SourceHCredential
                                 $HPSS = $SourceHPSS
                                 $CertCount = 1
                                    }
                            1 {
                                 ## Assigning values to variables.
                                 $HCertName = "CN="+$ReplicaHName
                                 $HCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq $HCertName )
                                 $HName = $ReplicaHName
                                 $H = $ReplicaH
                                 $HCredential = $ReplicaHCredential
                                 $ReplicaHPSS = New-PSSession -ComputerName $ReplicaH -Credential $ReplicaHCredential
                                 $HPSS = $ReplicaHPSS
                                 $CertCount = 2
                                    }
                      default {
                                 ## Message output.
                                 write-host "Fatal error encountered during the script execution! Reboot and continue the script!" -ForegroundColor Red
                                 ## Calling script exit function.
                                 FunctionSwitching ($FnSwitch = '11')
                                    }
            }
      ## Exception handling.
      try
          {
            ## Verifying the necessity of creating certificate for host.
            if ($HCert -eq $null -and $CertCount -le 2)
                {
                    ## Invoking commands on the remote host via remote PowerShell session.
                    $HDir = Invoke-Command -ComputerName $H -Credential $HCredential -ErrorAction Continue -ScriptBlock {
                    ## Exception handling.
                    try
                        {
                            ## Assigning value to variable.
                            $Dir=(Get-VMHost -ErrorAction Continue).VirtualMachinePath
                            ## Verifying the presence and availability of default location directory for the VM files on the host.
                            if((Test-Path $Dir -ErrorAction Continue) -eq $true)
                                {
                                   ## Returning the variable value.
                                   return ($Dir)
                                         }
                                            else
                                                  {
                                                    ## Generating error.
                                                    throw "Verify the presence and availability of default location directory ($Dir) for the VM files on the host $Using:HName!"
                                                        }
                                }
                                    catch
                                            {
                                                ## Checking for errors.
                                                if ($Error[0].Exception.Message -ne $null)
                                                    {
                                                        ## Message output.
                                                        write-error "Error verifying the temporary directory for $Using:H certificate!"
                                                        ## Calling script exit function.
                                                        FunctionSwitching ($FnSwitch = '11')
                                                            }
                                                    }
                                            }
                ## Creating certificate for the current host.
                New-SelfSignedCertificate -DnsName $HName -CertStoreLocation Cert:\LocalMachine\My -KeyLength 4096 -Hash SHA256 -KeyFriendlyName "HV Replication" -FriendlyName "HV Replication" -NotAfter $ExpDate -NotBefore "2020-01-01 01:00:00" -Signer $RootCert -ErrorAction Stop | Out-Null
                ## Assigning value to variable.
                $HCertFile = $MyPath+"\"+$HName+".pfx"
                ## Assigning value to variable. Exporting certificate.
                $HCert = ( Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -eq $HCertName ) | Export-PfxCertificate -FilePath $HCertFile -Password $Password -ChainOption BuildChain -ErrorAction Stop
                ## Copying certificate via Powershell session.
                copy-Item -Force -Confirm:$false -ToSession $HPSS $HCertFile $HDir -ErrorAction Stop
                ## Deleting the file with certificate on the current PC.
                Remove-Item -Path $HCertFile -Force -Confirm:$false -ErrorAction Stop
                ## Assigning value to variable.
                $HCertFile = $HDir+"\"+$HName+".pfx"
                ## Invoking commands on the remote host via remote PowerShell session.
                $CurentCert = Invoke-Command -ComputerName $H -Credential $HCredential -ErrorAction Stop -ScriptBlock {
                ## Exception handling.
                try
                    {
                        ## Deleting previous certificates from the host storage.
                        (Get-ChildItem Cert:\LocalMachine\Root | Where -Prop Subject -like *"CN=Hyper-V Replica Root CA") | Remove-Item -Force
                        (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$Using:HName) | Remove-Item -Force
                        ## Importing certificate.
                        $CurentCert = Import-PfxCertificate -FilePath $Using:HCertFile -CertStoreLocation "Cert:\LocalMachine\My" -Password $Using:Password -ErrorAction Stop | Out-Null
                        ## Deleting the file with certificate from the remote host.
                        Remove-Item -Path $Using:HCertFile -Force -Confirm:$false -ErrorAction SilentlyContinue
                        ## Assigning value to variable.
                        $RootCert = ( Get-ChildItem Cert:\CurrentUser\CA | Where -Prop Subject -eq "CN=Hyper-V Replica Root CA" )
                        ## Preparing location.
                        Push-Location
                        Set-Location "Cert:\LocalMachine\CA"
                        ## Transporting Root certificate to another storage.
                        Move-Item $RootCert.Thumbprint "Cert:\LocalMachine\Root" -Force -Confirm:$false -ErrorAction Stop
                        Pop-Location
                        ## Preparing location.
                        Push-Location
                        Set-Location "Registry::HKLM"
                        ## Verifying the necessity of adding information to registry.
                        if ((Test-Path "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\FailoverReplication" -IsValid) -eq $true)
                            {
                                ## Adding values to registry.
                                New-Item -Path "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization" -Name "FailoverReplication" -Force -Confirm:$false -ErrorAction Stop
                                Set-ItemProperty -Path "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\FailoverReplication" -Name DisableCertRevocationCheck -Value 1 -Type DWord -Force -Confirm:$false -ErrorAction Stop
                                Set-ItemProperty -Path "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Replication" -Name DisableCertRevocationCheck -Value 1 -Type DWord -ErrorAction Stop
                                ## Preparing location.
                                Pop-Location
                                    }
                        ## Returning the variable value.
                        return ($CurentCert)
                        }
                                catch
                                         {
                                            ## Message output.
                                            Write-Host $error[0].Exception.Message
                                                }
                            }
        ## Checking for errors.
        if ($Error[0].Exception.Message -eq $null)
            {
                ##  Messages output.
                Write-Host "Certificate for $HName host is successfully created and imported to $HName host!" -ForegroundColor Green
                Write-Host "Variables have been added to the $HName host registry!"-ForegroundColor Green
                    }    
         ## Verifying the current function mode.
         if ($CertCount -eq '1')
              {
                 ## Assigning value to variable.
                 $SourceHCert = $CurentCert
                 ## Calling next function.
                 FunctionSwitching ($FnSwitch = '6')
                     }
                         ## Verifying the current function mode.
                         elseif ($CertCount -eq '2')
                                {
                                  ## Assigning value to variable.
                                  $ReplicaHCert = $CurentCert
                                  ## Calling next function.
                                  FunctionSwitching ($FnSwitch = '7')
                                      }
                 }
                    else
                          {
                            ## Message output.
                            Write-Host "$HName host certificate already exists! Restart the script!" -ForegroundColor Red
                            ## Calling next function.
                            FunctionSwitching ($FnSwitch = '12')
                                }
                }
                    catch
                            {
                                ## Checking for errors.
                                if ($Error[0].Exception.Message -ne $null)
                                      {
                                        ## Messages output.
                                        Write-Host "$HName host certificate is not created or not imported on $HName host!" -ForegroundColor Red
                                        Write-Host "Variables were not added to $HName host registry!"-ForegroundColor Red
                                        ## Calling script exit function.
                                        FunctionSwitching ($FnSwitch = '11')
                                                }
                                    }
    ## Calling script exit function.
    FunctionSwitching ($FnSwitch = '11')
            }
  
## Function of verifying the input VM name.
function CheckInputVM
    {
        ## Assigning value to variable.
        $OutputFlag = $null
        ## Exception handling.
        try
            {
                ## Invoking commands on the remote host via remote PowerShell session.
                $VMs = Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ErrorAction Continue -ScriptBlock{
                                                                                                                                 ## Getting the list of VMs with disabled replication!
                                                                                                                                 Get-VM -ComputerName $Using:SourceH -Name * | where {$_.ReplicationState -eq 'Disabled' } | Format-Table Name, State
                                                                                                                                        }
                       }
                            catch
                                    {
                                        ## Checking for errors.
                                        if ($Error[0].Exception.Message -ne $null)
                                             {
                                                ## Message output.
                                                Write-Host "The list of VMs available for the replication from $SourceH is not available!" -ForegroundColor Red
                                                ## Calling script exit function.
                                                FunctionSwitching ($FnSwitch = '11')
                                                    }
                                            }
        ## Verifying the presence of the VMs with disabled replication.
        if ($VMs -ne $null)
            {
                ## Message output.
                Write-Host "On $SourceHName host the following VMs are available for replication to $ReplicaHName host:" -ForegroundColor White
                ## Available VMs list output.
                $VMs |Out-Host
                    }
                        else
                                {
                                    ## Message output.
                                    Write-Host "No VMs on $SourceHName host are available for replication to $ReplicaHName host!" -ForegroundColor Red
                                    ## Calling script exit function.
                                    FunctionSwitching ($FnSwitch = '12')
                                        }
        ## Getting parameters from the user.
        $VMsChoice =  Read-Host "Select the required replication option for the VMs unused in "$SourceHName" host replication: All unused / one of the unused / exit script? {A / O / Q}"
        ## Switching function mode.
        Switch ($VMsChoice)
                {
                    A
                        {
                            ## Message output.
                            Write-Host "All the VMs unused in $SourceHName replication!" -ForegroundColor Yellow
                            ## Assigning value to variable.
                            $OutputFlag = "All"
                            ## Calling next function.
                            FunctionSwitching ($FnSwitch = '8')
                                }
                    O
                        {
                            ## Message output.
                            Write-Host "One VM unused in $SourceHName host replication will be selected from the list!" -ForegroundColor Yellow
                            ## Assigning value to variable.
                            $OutputFlag = "One"
                            ## Calling next function.
                            FunctionSwitching ($FnSwitch = '8')
                                }
                    Q
                        {
                            ## Calling script exit function.
                            FunctionSwitching ($FnSwitch = '12')
                                }
                default
                        {
                            ## Message output.
                            write-host "You have entered an invalid value! Please, try again!" -foregroundcolor red
                            ## 2 seconds' delay before calling a function.
                            sleep 2
                            ## Calling next function.
                            FunctionSwitching ($FnSwitch = '7')
                                }
            }
     }
  
## VM selection confirmation function.
function ConfirmVMSelection
    {
       ## Verifying the current function mode.
       if ($OutputFlag -eq "One" -and $OutputFlag -ne $null)
           {
              ## Invoking commands on the remote host via remote PowerShell session.
              $VMs = Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ScriptBlock {
              ## Message output.
              Write-Host "The following VMs are available for replication on this host:" -ForegroundColor White
              ## Available VMs list output.
              Get-VM -ComputerName $Using:SourceH -Name * | where {$_.ReplicationState -eq 'Disabled' } | Format-Table Name, State | Out-Host
              $VMs =  Get-VM -ComputerName $Using:SourceH -Name *
              ## Returning the variable value.
              return ($VMs)
                   }
       ## Getting parameters from the user.
       $TmpVMs = read-host "Please, enter the name of the required VM"
       ## Verifying the current function mode.
       if ($VMs.Name -eq $TmpVMs)
          {
             ## Getting parameters from the user.
             $VMChoice = read-host "Enable replication for $TmpVMs on "$SourceHName" host? {Y/N}" 
             ## Invoking commands on the remote host via remote PowerShell session.
             $VMs =  Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ScriptBlock {
             $VMs =  Get-VM -ComputerName $Using:SourceH -Name $Using:TmpVMs
             ## Returning the variable value.
             return ($VMs)  
                  }
                       }
                           else
                                  {
                                      ## Message output.
                                      write-host -foregroundcolor red "You have entered an invalid value! Please, try again!"
                                      ## 2 seconds' delay before calling a function.
                                      sleep 2
                                      ## Calling next function.
                                      FunctionSwitching ($FnSwitch = '8')
                                           }
         }
            else
                    {
                       ## Invoking commands on the remote host via remote PowerShell session.
                       $VMs = Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ScriptBlock {
                       ## Message output.
                       Write-Host "The following VMs are available for replication on this host:" -ForegroundColor White
                       ## Available VMs list output.
                       Get-VM -ComputerName $Using:SourceH -Name * | where {$_.ReplicationState -eq 'Disabled' } | Format-Table Name, State | Out-Host
                       $VMs =  Get-VM -ComputerName $Using:SourceH -Name *
                       ## Returning the variable value.
                       return ($VMs)
                            }
                       ## Getting parameters from the user.
                       $VMChoice = read-host "Enable replication for all available VMs of $SourceHName host?{Y/N}"
                            }
   ## Switching function mode.
   Switch($VMChoice)
            {
              Y
                {
                    ## Calling next function.
                    FunctionSwitching ($FnSwitch = '9')
                        }
              N
                {
                    ## Calling next function.
                    FunctionSwitching ($FnSwitch = '7')
                        }
        default {
                    ## Message output.
                    write-host -foregroundcolor red "You have entered an invalid value! Please, try again!"
                    ## 2 seconds' delay before calling a function.
                    sleep 2
                    ## Calling next function.
                    FunctionSwitching ($FnSwitch = '7')
                        }
                  }
        }
  
## Function of starting VM replication.
function StartVMFailover
    {
     ## Zeroing ErrorVariable.
     $Error.Clear()
     ## Exception handling.
     try
          {
        ## Exception handling.
        try
            {
                ## Invoking commands on the remote host via remote PowerShell session.
                $ReplicaHVMs = Invoke-Command -ComputerName $ReplicaH -Credential $ReplicaHCredential -ErrorAction Continue -ScriptBlock    {
                    ## Exception handling.
                    try
                         {
                            ## Verifying for .
                            if ((get-VMReplicationServer).RepEnabled -eq $false)
                                {
                                    ## Assigning value to variable.
                                    $Dir=(Get-VMHost).VirtualMachinePath
                                    ## Verifying the current function mode.
                                    if($Using:IsDomainHost -ne $null)
                                        {
                                            ## Assigning value to variable.
                                            $HCert = (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$Using:ReplicaHName)
                                            ## Configuring replication on the side of the host with the replica with certificate.              
                                            Set-VMReplicationServer -ReplicationEnabled $True -ReplicationAllowedFromAnyServer $True -AllowedAuthenticationType Certificate -CertificateAuthenticationPort 443 -CertificateThumbprint $HCert.Thumbprint -DefaultStorageLocation $Dir -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                                                }
                                                    else
                                                            {
                                                                ## Configuring replication on the side of the host with the replica without certificate.
                                                                Set-VMReplicationServer -ReplicationEnabled $True -ComputerName $Using:ReplicaH -AllowedAuthenticationType Kerberos -ReplicationAllowedFromAnyServer $True -DefaultStorageLocation $Dir -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                                                                    }
                ## Assigning value to variable.
                $ReplicaHVMs =  Get-VM
                ## Returning the variable value.
                return ($ReplicaHVMs)
                                        }
                                            else
                                                    {
                                                         ## Generating error.
                                                         throw "Replication on the side of the host with the replica $Using:ReplicaHName is already enabled. Script execution can disrupt its work! Disable replication process and restart the script!"
                                                            }
                                 }
                                    catch
                                            {
                                                ## Message output.
                                                Write-Error $Error[0].Exception.Message  
                                                    }
            }
                    }
                        catch
                                {
                                    ## Message output.
                                    Write-Error $Error[0].Exception.Message
                                      }
         ## Checking for errors.
         if ($Error[0].Exception.Message -ne $null)
             {
                ## Message output.
                Write-Host "Replication cannot be configured on the side of the host with the replica $ReplicaHName!" -ForegroundColor Red
                ## Calling script exit function.
                FunctionSwitching ($FnSwitch = '11')
                     }
                       else
                            {
                                ## Message output.
                                Write-Host "Replication on the side of the host with the replica $ReplicaHName is successfully configured!" -ForegroundColor Green
                                        }
        ## Invoking commands on the remote host via remote PowerShell session.
        Invoke-Command -ComputerName $SourceH -Credential $SourceHCredential -ScriptBlock   {
        ## Exception handling.
        try
            {
                ## Verifying whether the replication was enabled before.
                if ((get-VMReplicationServer).RepEnabled -eq $false)
                    {
                        ## Assigning value to variable.
                        $Dir=(Get-VMHost).VirtualMachinePath
                        ## Verifying the current function mode.
                        if($Using:IsDomainHost -ne $null)
                            {
                                ## Assigning value to variable.
                                $HCert = (Get-ChildItem Cert:\LocalMachine\My | Where -Prop Subject -like *$Using:SourceHName)
                                ## Configuring replication on the side of the replicated host with certificate.
                                Set-VMReplicationServer -ReplicationEnabled $True -ReplicationAllowedFromAnyServer $True -AllowedAuthenticationType Certificate -CertificateAuthenticationPort 443 -CertificateThumbprint $HCert.Thumbprint -DefaultStorageLocation $Dir -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                                    }
                                        else
                                             {
                                                ## Configuring replication on the side of the replicated host without certificate.
                                                Set-VMReplicationServer -ReplicationEnabled $True -ComputerName $Using:SourceH -AllowedAuthenticationType Kerberos -ReplicationAllowedFromAnyServer $True -DefaultStorageLocation $Dir -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                                                  }
                            }
                               else
                                      {
                                         ## Verifying the current function mode.
                                         if ($OutputFlag -ne "All")
                                            {
                                                ## Generating error.
                                                throw "Replication on the side of the replicated host $Using:SourceH is already enabled. Script execution can disrupt its work! Disable replication process and restart the script!"
                                                }
                                           }
                        ## Checking for errors.
                        if ($Error[0].Exception.Message -eq $null)
                            {
                                ## Message output.
                                Write-Host "Replication of the replicated host $Using:SourceHName is successfully configured!" -ForegroundColor Green
                                          }
                                            else
                                                  {
                                                    ## Message output.
                                                    Write-Host "Configuration of the replicated host $Using:SourceHName cannot be finished!" -ForegroundColor Red
                                                    ## Message output.
                                                    Write-Error $Error[0].Exception.Message
                                                          }
                        ## Building a VMs foreach loop on the host.
                        foreach ($_ in $Using:VMs | where {$_.ReplicationState -eq 'Disabled' } )
                          {
                            ## Assigning value to variable.
                            $ReplEnable = $true
                            ## Building a VMs foreach loop on the host.  
                            foreach ($VM in $Using:ReplicaHVMs)
                                {
                                  ## Zeroing ErrorVariable.
                                  $Error.Clear()
                                  ## Verifying the current function mode.
                                  if (($VM).name -eq ($_).name)                                           
                                        {
                                            ## Assigning value to variable.
                                            $ReplEnable = $false
                                                 }
                                         }
                                   ## Verifying the current function mode.
                                   if ($ReplEnable -eq $true)                                           
                                        {
                                            ## Verifying the current function mode.
                                            if($Using:IsDomainHost -ne $null)
                                                {
                                                    ## Enabling the current VM replication.
                                                    Enable-VMReplication -VMName $_.Name -ReplicaServerName $Using:ReplicaHName -AuthenticationType Certificate -ReplicaServerPort 443 -CertificateThumbprint $HCert.Thumbprint -CompressionEnabled $true -RecoveryHistory 0 -ErrorAction SilentlyContinue -Confirm:$false | Out-Null
                                                        }
                                                            else
                                                                {
                                                                    ## Enabling the current VM replication.
                                                                    Enable-VMReplication -VMName $_.Name -ReplicaServerName $Using:ReplicaHName -ReplicaServerPort 80 -AuthenticationType Kerberos -CompressionEnabled $true -RecoveryHistory 0 -ErrorAction SilentlyContinue -Confirm:$false | Out-Null
                                                                        }
                                ## Checking for errors.
                                if ($Error[0].Exception.Message -eq $null)
                                    {
                                        ## Message output.
                                        Write-Host "Configuring replication "($_).Name" on $Using:ReplicaHName host is successfully finished!" -ForegroundColor Green
                                            }
                                               else
                                                    {
                                                        ## Message output.
                                                        Write-Host "Replication of "($_).Name" cannot be configured on $Using:ReplicaHName host!" -ForegroundColor Red
                                                        ## Message output.
                                                        Write-Error $Error[0].Exception.Message    
                                                              }
                                ## Start current VM replication.
                                Start-VMInitialReplication -VMName ($_).Name -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                                ## Checking for errors.
                                if ($Error[0].Exception.Message -eq $null)
                                    {
                                        ## Message output.
                                        Write-Host "The replication of the"($_).Name"on $Using:ReplicaHName host is successfully started!" -ForegroundColor Green
                                          }
                                            else
                                                  {
                                                    ## Message output.
                                                    Write-Host "Replication start cannot be finished!"($_).Name" on $Using:ReplicaHName host!" -ForegroundColor Red
                                                    ## Message output.
                                                    Write-Error $Error[0].Exception.Message
                                                        }
                                               }
                                                    else
                                                            {
                                                                ## Generating error.
                                                                throw "Replication ($_).Name configuration on $Using:ReplicaHName host cannot be finished! VM with this name already exists on Using:ReplicaHName host!"
                                                                ## Assigning values to variables.
                                                                $ReplEnable = $true
                                                                ## Zeroing ErrorVariable.
                                                                $Error.Clear() 
                                                                    }
                                }
                        }
                            catch
                                    {
                                        ## Message output.
                                        Write-Error $Error[0].Exception.Message  
                                             }
                                                }
            }
                catch
                        {
                            ## Checking for errors.
                            if ($Error[0].Exception.Message -ne $null)
                                {
                                    ## Messages output.
                                    Write-Host "Start and configuration of replication for the VM "($_).Name" on the host $Using:ReplicaHName have failed!" -ForegroundColor Red
                                    ## Calling script exit function.
                                    FunctionSwitching ($FnSwitch = '11')  
                                        }
                                            else
                                                  {
                                                    ## Calling next function.
                                                    FunctionSwitching ($FnSwitch = '10')
                                                        }
                        }
    ## Checking for errors.
    if ($Error[0].Exception.Message -eq $null)
      {
        ## Calling script exit function.
        FunctionSwitching ($FnSwitch = '10')
              }
                else
                      {
                           ## Calling script exit function.
                           FunctionSwitching ($FnSwitch = '11')
                                }
       }
## Script managing function.
function FunctionSwitching
    {
        ## Switching function mode.
        Switch($FnSwitch)
            {
                $null{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Temporary access right to work with any host in Trustedhosts of the current PC is granted!" -ForegroundColor Yellow
                        ## Starting new function.
                        SetNewSettings
                            }
                    1{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Verifying the availability of the host!" -ForegroundColor Yellow     
                        ## Starting new function.
                        CheckInputH
                            }
                    2{
                        ## Starting new function.
                        ConfirmHSelection
                            }
                    3{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Verifying Hyper-V host configuration!" -ForegroundColor Yellow
                        ## Starting new function.
                        ConfigureHosts
                            }
                    4{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Adding information about hosts to Hyper-V host hosts file!" -ForegroundColor Yellow
                        ## Starting new function.
                        AddtoEtcHosts
                            }
                    5{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Creating Root certificate on the current PC!" -ForegroundColor Yellow
                        ## Calling next function.
                        CreateRootCert
                            }
                    6{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Creating and importing certificate for the Hyper-V host!" -ForegroundColor Yellow
                        ## Calling next function.
                        AddCerttoHost
                            }
                    7{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Verifying the possibility of replicating VM!" -ForegroundColor Yellow
                        ## Calling next function.
                        CheckInputVM
                            }
                    8{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Verifying VMs available for replication!" -ForegroundColor Yellow
                        ## Calling next function.
                        ConfirmVMSelection
                            }
                    9{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Configuring and starting VM replication!" -ForegroundColor Yellow
                        ## Calling next function.
                        StartVMFailover
                            }
                   10{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "The script execution is finished!" -ForegroundColor Yellow
                        ## Calling script exit function.
                        ExitPS ($Flag = 'Exit')
                            }
                   11{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "The script execution is finished due to an error!" -ForegroundColor Red
                        ## Calling script exit function.
                        ExitPS ($Flag = 'Stop')
                            }
                   12{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "The script execution is finished before the due time!" -ForegroundColor Yellow
                        ## Calling script exit function.
                        ExitPS ($Flag = 'Stop') 
                            }
              default{
                        ## Messages output.
                        Write-Host "* * * *" -ForegroundColor Cyan
                        Write-Host "Fatal error encountered during the script execution! Reboot and continue the script!" -ForegroundColor Red
                        ## Calling script exit function.
                        ExitPS ($Flag -eq 'Stop')
                            }
                }
        }
## Emptying the screen.
Clear-Host
## Calling script managing function.
FunctionSwitching ($FnSwitch)

TO SUM UP

I’m not saying that this is the best option: code isn’t perfect. However, it is a useful option, and I’m sharing it with you as it is. If you want to improve, go ahead. Moreover, I’m not the one to avoid a discussion. That’s all, folks, hope this script will come in handy!

Hey! Found Volodymyr’s insights useful? Looking for a cost-effective, high-performance, and easy-to-use hyperconverged platform?
Taras Shved
Taras Shved StarWind HCI Appliance Product Manager
Look no further! StarWind HCI Appliance (HCA) is a plug-and-play solution that combines compute, storage, networking, and virtualization software into a single easy-to-use hyperconverged platform. It's designed to significantly trim your IT costs and save valuable time. Interested in learning more? Book your StarWind HCA demo now to see it in action!