How PowerCLI can help you Backup and Restore Distributed Switches

In my testing environment, I often find myself having to rebuild my vCenter Server after doing something spectacularly silly to mess it up beyond repair. I tend to have a fixed number of hosts, 3 to 5 on average, all connected to a common distributed switch (vDS). Any time disaster strikes, I always end up having to add the hosts and recreate the switch manually on the newly deployed vCenter Server.

After a while, I got fed up of this and found some time to put together a PowerCLI script to automate the process of reconnecting ESXi hosts and re-creating distributed switching on a freshly deployed vCenter Server. You’ll find my script below. If you’re new to PowerCLI, have a look at A PowerCLI Primer to get you started.

 

Backing up the Configuration of Distributed Switches


Saving the configuration of any distributed switch(s) you might have, is one habit you should get into asap. Doing this gives you the ability to restore any vDS and its settings on an existing or new vCenter. The warning shown in the next screenshot is what you’re greeted with anytime you add an ESXi host to vCenter that was previously hooked up to a vDS that no longer exists. Being able to restore the vDS and its configuration avoids this.

Error message returned when a host is added to a VC that's missing the original vDS the host was connected to

Error message returned when a host is added to a VC that’s missing the original vDS the host was connected to

 

To manually save or restore a vDS configuration, simply right-click on the switch’s name and choose Export Configuration from the Settings menu. You will then be prompted to save the exported configuration as a zipped file. Below, you will see how PowerCLI can be used to automate the process.

using Power CLI to save vds switch settings

 

PowerCLI Commands Used Today


From a PowerShell and PowerCLI perspective, the script is pretty straightforward, more so if you’re used to scripting. The main PowerCLI cmdlets I used in the script are the ones listed below. Click on each to visit the official documentation page for more information.

 

Today’s Script Explained


Let me start by saying that this script should only be used for testing purposes. It will not migrate anything else other than ESXi hosts and any distributed switches it finds. The target vCenter Server, should ideally be a freshly installed vCenter Server. Although I included a few basic checks, the script, for instance, will fail to import a vDS if it finds another one with the same name on the target vCenter. Likewise, it will create a new datacenter called DC if it finds none or will fall to using the first DC returned by (Get-Datacenters)[0].

The script’s main function is called migrate, which does all the work. The entry point of the script commented as such verifies that it can connect both to the source and target vCenters. If either or both of the connection attempts fail, the script will exit otherwise it calls migrate and does the following:

  1. Get a list of ESXi hosts and distributed switches on the source vCenter Server (Lines 26-27).
  2. Given a minimum of 1 vDS, export the switches’ configuration to the user’s Windows desktop. $vDScount keeps count of the number of vDSes (Lines 32-38).
  3. Disconnect any existing ESXi host from the source VC removing it from the inventory (Lines 40-46).
  4. Check if there’s a DC created on the target VC. If not, create one called DC since we need it to be able to import vDSes. (Line 55).
  5. Add the ESXi hosts managed by the source VC to the target VC. We use $ESXHosts for this. (Lines 57-60 & Line 26).
  6. Import the saved vDSes configuration. We use New-VDSwitch to do this using the BackupPath parameter to specify the distributed switches configuration file. (Lines 62-65).

Note: $ESXHosts can be initialized as an array containing the DNS names or IP addresses of the ESXi hosts you want to add to the new VC. With some additional work, the same can be done for any vDS assuming configuration backups are available.

 

Requirements


The script requirements for it to work properly are listed as follows:

  • Run the script from an administrative PowerCLI shell. I’ve used PowerCLI 6.5 R1.
  • The script must be run off a computer running Windows.
  • The source vCenter Server must be able to reply to API calls.

In this video, I demonstrate how the script works along with the steps carried out the results of which can be seen in the stacked vSphere client windows.

 

The Script


###########################################
# Change values as required               #
###########################################

 $srcVC="192.168.0.1"
 $trgVC="192.168.0.2"
 $vDSConfigPath="$env:USERPROFILE\Desktop\"
 $srcAdm = "[email protected]"
 $trgAdm = "[email protected]"
 $srcPwd = "vmware!667"
 $trgPwd = "vmware!667"
 $ESXRoot = "root"
 $ESXPwd = "vmware!667"

############################################

function migrate{

 $vDScount = 0

#Source vCenter Server
 Write-Host ("Running tasks on source VC") -ForegroundColor Cyan
 Write-Host ("--------------------------") -ForegroundColor Cyan

 $ESXHosts = Get-VMHost -Server $srcVC
 $vDSwitches = Get-VDSwitch -Server $srcVC

#Export vDS
 Write-Host ("Exporting distributed switches configuration")

 if ($vDSwitches){
  ForEach ($vDS in $vDSwitches){
    $vDScount++
    Export-VDSwitch -VDSwitch $vDS -Destination ($vDSConfigPath + "vDS" + $vDScount + ".zip") -Force | out-null
  } 
 }else
  {Write-Host "No distributed switches found"}

#Disconnect and remove hosts from inventory
  ForEach ($ESXi in $ESXHosts){
   Write-Host ("Disconnecting " + $ESXi.name) 
   Set-VMHost -vmhost $ESXi -Server $srcVC -State "Disconnect" -Confirm:$false | Out-Null
   Write-Host ("Removing " + $ESXi.name + "`n") 
   Remove-VMHost $ESXi.name -Server $srcVC -Confirm:$false | Out-Null
  } 

 Write-Host ("`nDisconnecting from source VC") -ForegroundColor Red
 $srcVCconn | Disconnect-VIServer -Confirm:$false

 Write-Host ("`n`nRunning tasks on target VC") -ForegroundColor Cyan
 Write-Host ("--------------------------") -ForegroundColor Cyan

#Target vCenter Server
 if (!(Get-Datacenter)) {New-Datacenter -Name "DC" -location (Get-folder -NoRecursion) | Out-Null}

 Foreach ($ESXi in $ESXHosts){
  Write-Host ("Adding " + $ESXi.name) 
  Add-VMHost $ESXi.name -Location (Get-Datacenter)[0] -User $ESXRoot -Password $ESXPwd -Force -Confirm:$false | Out-Null
 }

 for ($c=1; $c -le $vDScount; $c++){
  Write-Host ("`nImporting distributed switches ... ") 
  New-VDSwitch -BackupPath ($vDSConfigPath + "vDS" + $c + ".zip") -Location (get-Datacenter)[0] -KeepIdentifiers | Out-Null
 }

 Write-Host ("Disconnecting from target VC") -ForegroundColor Red
 $trgVCconn | Disconnect-VIServer -Confirm:$false
 }

######################
# Script entry point #
######################

 if ($DefaultVIServers -ne $null) {Disconnect-VIServer * -Confirm:$false -Force | Out-Null}

 $srcVCconn = Connect-VIServer $srcVC -user $srcAdm -Password $srcPwd -Force
 $trgVCconn = Connect-VIServer $trgVC -user $trgAdm -Password $trgPwd -Force

 if ($srcVCconn.IsConnected -and $trgVCconn.IsConnected){
  clear
  Write-host ("Connected to " + $srcVCconn.name + " (" + $srvVCConn.ExtensionData.Content.About.FullName + ")") 
  Write-host ("Connected to " + $trgVCconn.name + " (" + $trgVCConn.ExtensionData.Content.About.FullName + ")`n")

  migrate} else
  {Write-Host "Source or target VC is offline" 
   exit
 }

 

Conclusion


It’s always good practice to back up the configuration of any distributed switches you might have in your vSphere environment. Today, we’ve seen how you can automate the process and presented a use-case where PowerCLI is used to export and re-import a vDS configuration allowing ESXi hosts to be successfully reconnected to vCenter without hiccups. As mentioned, the script should be used in testing environments, speaking of which, How to set up a nested vSphere 6 environment is a good place to start if you’ve never set up a vSphere environment for testing purposes.

If you find the script useful or would like to see something changed, corrected or included, please feel to drop a comment down below.

[the_ad id=”4738″][the_ad id=”4796″]

Altaro VM Backup
Share this post

Not a DOJO Member yet?

Join thousands of other IT pros and receive a weekly roundup email with the latest content & updates!

Leave a comment

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