ESXi Patching Using PowerCLI
ESXi Patching Using PowerCLI

ESXi Patching Using PowerCLI

Content:

  • Introduction
  • Advantages of using PowerCLI to Upgrade an ESXi Host
  • Prerequisites
  • Steps to Upgrade ESXi
  • Full Script
  • An alternative approach using esxcli commands
  • Conclusion

Introduction

Upgrading an ESXi host is an essential task for maintaining a stable and secure virtual environment. With the help of PowerShell, the upgrade process can be automated, reducing the potential for human error and saving time. In this blog post, we will discuss how to upgrade an ESXi host using PowerShell, including placing the host in maintenance mode and waiting for the maintenance mode event to complete.

Advantages of using a PowerShell script to upgrade an ESXi host:

  • Efficiency: Automating the upgrade process using PowerShell can save a significant amount of time compared to manually upgrading each host.
  • Consistency: By using the same script for each upgrade, you can ensure that the upgrade process is consistent across all hosts, reducing the potential for human error.
  • Reliability: The use of PowerShell can reduce the potential for errors and oversights that can occur during manual upgrades, resulting in a more reliable upgrade process.
  • Flexibility: The script can be easily customized to meet the specific needs of your environment, such as adding custom VIBs or modifying the maintenance mode options.
  • Scalability: The script can be used to upgrade multiple hosts simultaneously, making it ideal for larger environments.

By leveraging the power of PowerShell, you can streamline and simplify the ESXi upgrade process, resulting in a more efficient and reliable infrastructure.

Get book for Learning PowerCLI: denNieuwendijk, Robert van: Amazon.in

Prerequisites

Before beginning the upgrade process, you will need to ensure that you have the following:

  • An ESXi host that needs to be upgraded
  • A compatible ESXi upgrade bundle downloaded from the VMware website
  • PowerShell installed on your system
  • VMware PowerCLI installed on your system

Step 1: Connect to the ESXi Host

Connect-VIServer -Server <ESXi-host> -User <Username> -Password <Password>

Step 2: Place the ESXi Host in Maintenance Mode

Set-VMHost -VMHost <ESXi-host> -State "Maintenance" -Confirm:$false

Step 3: Wait for the Maintenance Mode Event to Complete

The while loop waits until an event with this message is found, indicating that the maintenance mode has completed.

PowerShell Code Showcase

$event = Get-VIEvent -Start (Get-Date).AddSeconds(-30) -MaxSamples 1000 | Where-Object {$_.FullFormattedMessage -like "*entered maintenance mode*"}

while ($event -eq $null) {

    Write-Host "Waiting for maintenance mode to complete..."

    Start-Sleep -Seconds 10

    $event = Get-VIEvent -Start (Get-Date).AddSeconds(-30) -MaxSamples 1000 | Where-Object {$_.FullFormattedMessage -like "*entered maintenance mode*"}

}

Step 4: Create a New ESXi Image Profile for the Upgrade

Next, you will need to download the patch file from the VMware path download site:

VMware Patch Site

Add-EsxSoftwareDepot -DepotUrl "C:\esxi-depot.zip"
$newProfileName = "<new-profile-name>"
$newProfile = New-EsxImageProfile -CloneProfile -ProfileName $newProfileName -Vendor "ESXi"

Step 5: Add the Upgrade Bundle to the New Image Profile

$upgradeBundlePath = "<path-to-upgrade-bundle>"
Add-EsxSoftwarePackage -ImageProfile $newProfile -SoftwarePackage $upgradeBundlePath

Step 6: Validate the New Image Profile

Test-EsxImageProfile -ImageProfile $newProfile

Step 7: Apply the Upgrade to the ESXi Host

Set-EsxImageProfile -ImageProfile $newProfile -VMHost <ESXi-host> -NoSignatureCheck -NoAutoReboot -Confirm:$false

Step 8: Verify the Upgrade

Get-VMHost <ESXi-host> | Select-Object Version, Build, Name

Full Script

Below is the full script, I try to put all the above actions into a function.

PowerShell Code Showcase

function Upgrade-ESXiHost {

    [CmdletBinding()]

    param(

        [Parameter(Mandatory=$true)]
        [string]$EsxiHost,
        [Parameter(Mandatory=$true)]
        [string]$UpgradeBundle,
        [string]$CustomVibPath = "",
        [int]$Timeout = 3600
    )
    $maintenanceModeEvent = New-Object Vmware.Vim.HostMaintenanceModeEvent
    $serviceInstance = Get-View ServiceInstance
    $host = Get-VMHost $EsxiHost
    # Place the host in maintenance mode
    Write-Host "Placing $EsxiHost in maintenance mode..."
    $task = $host.EnterMaintenanceMode($Timeout, $maintenanceModeEvent)
    Wait-Task $task
    # Validate the upgrade bundle
    Write-Host "Validating upgrade bundle..."
    $newProfile = Add-EsxSoftwareDepot $UpgradeBundle
    Test-EsxImageProfile -ImageProfile $newProfile

    # Add custom VIBs if specified
    if ($CustomVibPath) {

        Write-Host "Adding custom VIBs..."

        $vibBundle = Add-EsxSoftwareDepot $CustomVibPath

        Add-EsxSoftwarePackage -ImageProfile $newProfile -SoftwarePackage $vibBundle.ExtensionData

    }
    # Apply the upgrade to the host
    Write-Host "Applying upgrade to $EsxiHost..."
    Set-EsxImageProfile -ImageProfile $newProfile -VMHost $EsxiHost -NoSignatureCheck -NoAutoReboot -Confirm:$false
    # Wait for the upgrade to complete

    Write-Host "Waiting for upgrade to complete..."
    while ((Get-VMHost $EsxiHost).Runtime.ConnectionState -ne "Connected") {
        Start-Sleep -Seconds 10
    }
    # Exit maintenance mode
    Write-Host "Exiting maintenance mode for $EsxiHost..."
    $task = $host.ExitMaintenanceMode($Timeout)
    Wait-Task $task
}
        

To use this function, simply call it with the required parameters:

Upgrade-ESXiHost -EsxiHost "hostname" -UpgradeBundle "C:\ESXi650-201912001.zip" -CustomVibPath "C:\CustomVibs.zip" 

To scale this function to multiple hosts, you can use PowerShell remoting to run the function on each host remotely. Here's an example of how you can do this:

PowerShell Code Showcase

$hosts = "esxi-host1", "esxi-host2", "esxi-host3"

$session = New-PSSession -ComputerName $hosts

Invoke-Command -Session $session -ScriptBlock { 
    param(
        [Parameter(Mandatory=$true)]
        [string]$EsxiHost,

        [Parameter(Mandatory=$true)]
        [string]$UpgradeBundle,

        [string]$CustomVibPath = "",

        [int]$Timeout = 3600
    )

    Upgrade-ESXiHost -EsxiHost $EsxiHost -UpgradeBundle $UpgradeBundle -CustomVibPath $CustomVibPath -Timeout $Timeout
} -ArgumentList "esxi-host1", "C:\ESXi650-201912001.zip", "C:\CustomVibs.zip"

Remove-PSSession $session
       

An alternative approach using esxcli commands:

PowerShell Code Showcase

# Set the connection details

$HostIP = "192.168.XX.XX"
$Username = "root"
$Password = "password"

# Enable SSH service on the ESXi host
Set-VMHostService -VMHost $HostIP -Enabled:$true -Service "TSM-SSH"

# Connect to the ESXi host over SSH(Before running this make sure you Posh-SSH PowerShell module installed )

$session = New-SSHSession -ComputerName $HostIP -Credential (New-Object System.Management.Automation.PSCredential ($Username, (ConvertTo-SecureString -String $Password -AsPlainText -Force)))

# Define the esxcli command to upgrade ESXi (you can put the zip files on the datastore and provide the full path )

$esxcliCommand1 = "esxcli software profile update -d https://path/to/upgrade/bundle.zip -p ESXi-7.0U2a-18644231-standard"

# Define the esxcli command to update software packages
$esxcliCommand2 = "esxcli software vib update -d https://path/to/update/zipfile.zip"

# Run the esxcli commands remotely
$esxcliOutput1 = Invoke-SSHCommand -SessionId $session.SessionId -Command $esxcliCommand1

$esxcliOutput2 = Invoke-SSHCommand -SessionId $session.SessionId -Command $esxcliCommand2

# Disconnect from the ESXi host
Remove-SSHSession -SessionId $session.SessionId

# Disable SSH service on the ESXi host
Set-VMHostService -VMHost $HostIP -Enabled:$false -Service "TSM-SSH"

# Display the output of the esxcli commands
Write-Host "Output of $esxcliCommand1 on $HostIP:"
Write-Host $esxcliOutput1.Output
Write-Host "Output of $esxcliCommand2 on $HostIP:"
Write-Host $esxcliOutput2.Output
       

Conclusion

Automating the upgrade process using PowerShell can save time and reduce the potential for human error. By following the steps outlined in this blog post, you can easily upgrade your ESXi hosts in a more efficient and reliable manner.


Siddartha Kumar Das
About Siddartha Kumar Das

Tech Enthusiast

Topics