VMware Cloud Community
DyJohnnY
Enthusiast
Enthusiast

How to determine if vCenter PowerCLI session is still connected to vCenter

Hi,

I'm writing a batch script that will changes on esxi hosts.

It does following:

#connect to 1 or multiple vCenters

#gets all esxi hosts

#Create batches of hosts

foreach batch in batches {

     #1# Put hosts in maintenance mode

     #2# make the change

     #3# Reboot hosts

     #4# exit maintenance mode

     }

The issue we've had was that during the script execution is that at any of the stages 1,2,3,4 from above, our vCenter session gets disconnected. Last time it was because we had a vCenter service crash.

I am looking for a way to handle this kind of error within the script logic, so for a way to monitor if my vCenter session is still working, before issuing any of the 1-4 tasks.

Sofar what i've come up with is bit:

Function Test-vCenterSession ([Parameter(Mandatory=$true)]$vcenter) {

    $svcRef = new-object VMware.Vim.ManagedObjectReference

    $svcRef.Type = “ServiceInstance”

    $svcRef.Value = “ServiceInstance”

    try {

        $alive = (get-view $svcRef -Server $vcenter -ErrorAction SilentlyContinue -ne $null)

        }

    catch {

        Write-Warning "Could not get ServiceInstance for $vcenter"

        $alive = $false

        }

    Return $alive

    }

$vcenter = "vcenter.demo"

Test-vCenterSession $vcenter

Is there perhaps an easier way to achieve this?

thank you,

ionut

IonutN
0 Kudos
0 Replies