Move an Connected ESXi host between vCenters via PowerCLI


A interactive PowerCLI script to disconnect an ESXi host (not in maintenance mode) from the source vCenter and add to a cluster on the destination vCenter.
Each VC is NOT in the same SSO domain.
The end goal is to drain the source vCenter of all hosts so the old vCenter can be decommissioned.

This assumes due diligence in recording DRS/SDRS rules, vDS/VMK’s.

VMware PowerCLI
vCenter – 7.0.2, 17694817
VMware ESXi – 7.0.2, 17867351

# Move an Connected ESXi host between vCenters via PowerCLI 
# found

# thanks for the SecurePassword function

Function ConvertFrom-SecureToPlain {
    param( [Parameter(Mandatory=$true)][System.Security.SecureString] $SecurePassword)
    # Create a "password pointer"
    $PasswordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
    # Get the plain text version of the password
    $PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PasswordPointer)
    # Free the pointer
    # Return the plain text password

# Setup Variables
$vCenter_Source = Read-Host "Enter the FQDN of the Source vCenter"
$vmhost = Read-host "Enter in the FQDN of the ESXi host"
$SecurePassword = Read-Host "Enter ESXi Root Password" -AsSecureString
$Password = ConvertFrom-SecureToPlain ($SecurePassword)
$vCenter_Destination = Read-Host "Enter the FQDN of the Destination vCenter"
$Cluster = Read-host "Enter in the Destination Cluster Name"

# Connect to your Source vCenter and Disconnect the ESXi host
Connect-VIServer $vCenter_Source | Out-Null
Write-Host " "
Read-Host "Hit ENTER to Disconnect ESXi host - $vmhost"
Set-VMHost -VMHost $vmhost -State "Disconnected"

# Remove ESXi host
Write-Host " "
Read-Host "Hit ENTER to Remove ESXi host $vmhost from vCenter $vCenter_Source"
Remove-VMHost -VMHost $vmhost -Confirm:$false

# Disconnect from the Source vCenter
Disconnect-VIServer $vCenter_Source -Force -Confirm:$false

# Wait 10 Seconds
Start-Sleep -Seconds 10

# Connect to the Destination vCenter and add the ESXi host to the cluster
Connect-VIServer $vCenter_Destination | Out-Null
Write-Host " "
Add-VMHost $vmhost -location $Cluster -user root -password $Password -force:$true

# Disconnect from the Destination vCenter
Disconnect-VIServer $vCenter_Destination -Confirm:$false