HCX - PowerCli operations and best practices
search cancel

HCX - PowerCli operations and best practices

book

Article ID: 321585

calendar_today

Updated On:

Products

VMware HCX

Issue/Introduction

This document consists of information about PowerCLI installation, upgrade and procedure to perform HCX migration using PowerCLI.

Environment

VMware HCX

Resolution

IMPORTANT: PowerShell software should be installed and running minimum 3.0 version on the system used for installation of PowerCLI module.

  • To access PowerShell use the command "pwsh". Refer PowerShell install DOC for more detail.
# pwsh
PowerShell 7.2.1
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

   A new PowerShell stable release is available: v7.3.1
   Upgrade now, or check out the release page at:
     https://aka.ms/PowerShell-Release?tag=v7.3.1

PS />
PS /> Install-Module -Name VMware.PowerCLI

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to
 install the modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A
Installing package 'VMware.PowerCLI' [Installing dependent package 'VMware.Sdk.Nsx.Policy'                           ]
Installing package 'VMware.Sdk.Nsx.Policy' [Downloaded 18.70 MB out of 18.70 MB.
  • Post installation, check the PowerCLI version.
PS /> Get-PowerCLIVersion

PowerCLI Version
----------------
   VMware.PowerCLI 13.0.0 build 20829139
---------------
Component Versions
---------------
   VMware Common PowerCLI Component 13.0 build 20797081
   VMware Cis Core PowerCLI Component PowerCLI Component 13.0 build 20797636
   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 13.0 build 20797821
PS />

Note:- To get more info about new features or changes added to HCX for a specific PowerCLI version, please refer PowerCLI Release Notes.

  • To upgrade PowerCLI version, use "update-module" command.
Update-Module VMware.powerCLI

HCX migration using PowerCLI

STEP-1

  • First we need to create a variable to store login credentials(SSO) with respect to Source HCX manager locally on the system. This $credential variable will be used later in STEP-2.
PS /> $credential = Get-Credential

PowerShell credential request
Enter your credentials.
User: [email protected]
Password for user [email protected]: ****************

PS />
PS />
PS /> $credential | Export-Clixml -Path /demo.cred

Note:- The demo.cred file content is encrypted(password) and only be used with the account it was created, also the PC where it was created originally.

IMPORTANT: The credential file can’t be shared over a network share or to be sent to someone else for their use.

PS /> ls -l | grep demo
-rw-r--r--   1 root root  465 Feb 28 11:46 demo.cred
PS />

PS /> cat ./demo.cred
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCredential</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Management.Automation.PSCredential</ToString>
    <Props>
      <S N="UserName">[email protected]</S>
      <SS N="Password">#####</SS>
    </Props>
  </Obj>
</Objs>

STEP-2

  • Connect to the Source HCX manager using Connect-HCXServer cmdlet. Please refer Connect-HCXServer DOC for more info.
PS /> Connect-HCXServer 10.x.91.x -Credential $credential

Server                         User
------                         ----
10.x.91.x                   [email protected]

Note:- In the above example "10.x.91.x" is the Source HCX manager IP address.

STEP-3

  • Set up a variable $vm with respect to Source VM going to be migrated using HCX.
$vm = Get-HCXVM -Name "demo_vm"

Note:- And 'YES', we can use a FOR loop to read the SOURCE VM name or names from a file (.txt or .csv) . However, that is not under the scope of this document.
Reference:- Get-HCXVM

STEP-4

  • Set up variables $HcxSrcSite and $HcxDstSite with respect to the Source Site and Destination Site for a given migration.
$HcxSrcSite = Get-HCXSite -Source '10.x.90.y'
$HcxDstSite = Get-HCXSite -Destination 'vcenter.xxxxxxxx.example.com'
  • In order to select respective source and target site information the below cmdlets need to be executed and with the help of it the variables  $HcxSrcSite and $HcxDstSite will get assigned respective values.
PS /> Get-HCXSite -Source

Type Name                                               Id
---- ----                                               --
VC   10.x.90.y                                      a316200d-####-####-####-##########ea
PS /> Get-HCXSite -Destination

Type Name                                               Id
---- ----                                               --
VC   vcenter.xxxxxxxxx.example.com             227714b9-####-####-####-##########11

Reference:- Get-HCXSite

STEP-5

  • Set up a variable $sourceNetwork with respect to Source VM network info
$sourceNetwork = $vm.Network[0]

IMPORTANT:- Please ensuse to refer Network object here.
Reference:- Get-HCXVM

STEP-6

  • Set up a variable $targetNetwork for the Target network where the Source VM after migration will connect or reside.
$targetNetwork = get-HCXNetwork -Type NsxtSegment -Name 'Segment1' -Site $HcxDstSite
  • In order to get the -Name parameter value Segment1 we need to execute the below cmdlet in order to print the List of available networks available at the target site and then select the required one.
PS /> get-HCXNetwork -Type NsxtSegment -Site $HcxDstSite

Name                                                       Type                         Id
----                                                       ----                         --
Segment1                                                   NsxtSegment                  /infra/tier-1s…
Segment2                                                   NsxtSegment                  /infra/tier-1s…

Reference:- Get-HCXNetwork

STEP-7

  • Map the Source network to the target network with the help of a variable $NetworkMapping
$NetworkMapping = New-HCXNetworkMapping -SourceNetwork $sourceNetwork -DestinationNetwork $targetNetwork

Reference:- New-HCXNetworkMapping

STEP-8

  • Set up a variable $DstFolder with respect to the Destination folder where the VM data is going to reside.
$DstFolder = Get-HCXContainer -Site $HcxDstSite -Type Folder -Name 'Workloads'

Reference:- Get-HCXContainer

STEP-9

  • Set up a variable $DstCompute with respect to the Destination Compute Resource attribute.
$DstCompute = Get-HCXContainer -Site $HcxDstSite -Type "ResourcePool" -Name 'Compute-ResourcePool'

Reference:- Get-HCXContainer

STEP-10

  • Set up a variable $DstDatastore with respect to Destination Datastore.
$DstDatastore = Get-HCXDatastore -Site  $HcxDstSite -Name WorkloadDatastore

Reference:- Get-HCXDatastore

STEP-11

  • Setup a variable $DemoMigration using cmdlet New-HCXMigration with the help of all the above mentioned variables.
$DemoMigration = New-HCXMigration -VM $vm `
 -MigrationType Rav `
 -SourceSite $HcxSrcSite `
 -DestinationSite $HcxDstSite `
 -Folder $DstFolder `
 -TargetComputeContainer $DstCompute `
 -TargetDatastore $DstDatastore `
 -DiskProvisionType "Thin" `
 -NetworkMapping $NetworkMapping `
 -RemoveSnapshots $true `
 -ForcePowerOffVm $true

Reference:- New-HCXMigration

STEP-12

  • Validate the above mentioned migration workflow using cmdlet Test-HCXMigration
PS /> Test-HCXMigration $DemoMigration

ValidationResult                                                                 Name
----------------                                                                 ----
{RAV service is not enabled on the deployed Service Mesh}                        vm-94
{Validation is Failed, There are one or more errors}
  • The above error is due to the reason that the Service mesh between the Source and Target site used for migration is provisioned for BULK migration only.
  • Now, if we change the migration type to Bulk, then the validation will succeed.
$DemoMigration = New-HCXMigration -VM $vm `
 -MigrationType Bulk `
 -SourceSite $HcxSrcSite `
 -DestinationSite $HcxDstSite `
 -Folder $DstFolder `
 -TargetComputeContainer $DstCompute `
 -TargetDatastore $DstDatastore `
 -DiskProvisionType "Thin" `
 -NetworkMapping $NetworkMapping `
 -RemoveSnapshots $true `
 -ForcePowerOffVm $true
PS /> Test-HCXMigration $DemoMigration

ValidationResult                                                                 Name
----------------                                                                 ----
{Validation is Successful, You can proceed with Migration}                       vm-94

Reference:- Test-HCXMigration

STEP-13

  • Start migration using cmdlet Start-HCXMigration
PS /> Start-HCXMigration -Migration $DemoMigration -Confirm:$false

VM                             Migratio State                Id
                               nType
--                             -------- -----                --
demo_vm                        Bulk                          c8d463fe-####-####-####-##########9d

Reference:- Start-HCXMigration

STEP-14

  • Check the STATUS of migration using cmdlet Get-HCXMigration
PS /> Get-HCXMigration

VM                             Migratio State                Id
                               nType
--                             -------- -----                --
demo_vm                        Bulk     MIGRATION_STARTED    c8d463fe-####-####-####-##########9d
host_c                         Bulk     MIGRATED             609cded3-####-####-####-##########54
host_b                         Bulk     MIGRATED             59b901bd-####-####-####-##########59
host_a                         Bulk     MIGRATED             3605bc70-####-####-####-##########63

PS /> Get-HCXMigration -State "MIGRATING"

VM                             Migratio State                Id
                               nType
--                             -------- -----                --
demo_vm                        Bulk     TRANSFER_STARTED     c8d463fe-####-####-####-##########49

PS /> Get-HCXMigration -State "MIGRATING"

VM                             Migratio State                Id
                               nType
--                             -------- -----                --
demo_vm                        Bulk     SWITCHOVER_STARTED   c8d463fe-####-####-####-##########9d



Reference:- Get-HCXMigration

STEP-15

  • And once the migration completes
PS /> Get-HCXMigration -State "MIGRATING"
PS />
PS />
PS /> Get-HCXMigration -State "MIGRATED"

VM                             Migratio State                Id
                               nType
--                             -------- -----                --
demo_vm                        Bulk     MIGRATED             c8d463fe-####-####-####-##########9d
host_c                         Bulk     MIGRATED             609cded3-####-####-####-##########54
host_b                         Bulk     MIGRATED             59b901bd-####-####-####-##########59
host_a                         Bulk     MIGRATED             3605bc70-####-####-####-##########63

PowerCLI logging (Error/Exception)

In order to capture the exception or Error in a PowerCLI script during execution a try, catch block can be used , however, it works only with terminating error.

Below PowerCLI code(demo.ps1) can be used to get VM inventory from a HCX manager.

$vm_name = Read-Host -Prompt 'Type VM Name'
$info = try
{
  write-host -ForegroundColor Yellow "Getting VM Inventory"
  write-host " "
  get-hcxvm -Name $vm_name -ErrorAction Stop
}
catch
{
  write-error $_.Exception.Message
  $_ |select -expandproperty invocationinfo
}

echo $info

In the above code we are using get-hcxvm cmdlet along with try, catch block. However, we are using a parameter ErrorAction with value as STOP in order to make it terminating error.  This will print the error or exception along with Line number of the code causing the script or code to fail.

PS /> ./demo.ps1
Type VM Name: test
Getting VM Inventory from ESXi host

Write-Error: 03/22/2023 11:58:27    Get-HCXVM        Could not find HCXVM with Name 'test'.

MyCommand             : Get-HCXVM
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 6
OffsetInLine          : 3
HistoryId             : 8
ScriptName            : /demo.ps1
Line                  :   get-hcxvm -Name $vm_name -ErrorAction Stop

PositionMessage       : At /demo.ps1:6 char:3
                        +   get-hcxvm -Name $vm_name -ErrorAction Stop
                        +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot          : /
PSCommandPath         : /demo.ps1
InvocationName        : get-hcxvm
PipelineLength        : 0
PipelinePosition      : 0
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :




Additional Information

To collect the error in detail, you can use the following command:

$error[0] | select *