Display list of Multiple vCenter Servers to connect to in your PowerCLI Scripts

If you’re company anything like mine, you probably have multiple vCenter servers in your environment.  They may be linked, they may not.  In my environment, we have 4 vCenter servers we consider Production, even though one is for QA, and we have a lab environment.

Normally, I just connect to vCenter manually in PowerCLI before I run a command/script to make a change, run a report, etc.  But then I got to thinking, wouldn’t it be easier if I just had something to include at the beginning of my scripts to provide a list.  Something I could put in the beginning of each script…

################################
#
# PowerCLI script with list of vCenter servers
# Created by BLiebowitz on 11/11/2015
#
################################

# List vCenters to connect to

Write-host "Select which vCenter to connect to:"
Write-Host ""
Write-Host "1. vCenter1"
Write-Host "2. vCenter2"
Write-Host "3. vCenter3"
Write-Host "4. vCenter4"

$Ivcenter = read-host “Select a vCenter Server. Enter Number “

if ($Ivcenter –eq 1) {
$vcenter = "vCenter1"
} elseif ($Ivcenter -eq 2) {
$vcenter = "vCenter2"
} elseif ($Ivcenter -eq 3) {
$vcenter = "vCenter3"
} else {
$vcenter = "vCenter4"
}

write-host ""
Write-Host "You Picked: "$vcenter
write-host ""
start-sleep -s 3

{
# Connect to vCenter
connect-viserver $vcenter

# perform the work you wanted to perform.  use the $vcenter variable for the vCenter server name.

}
# Disconnect from vCenter
disconnect-viserver $vcenter -confirm:$false
}

If you wanted, for some reason, to connect to EVERY vCenter (one at a time), you can do this instead.  Keep in mind, it will not prompt you to choose, it will login to vCenter1, perform the task, disconnect, then repeat with vCenter2, etc.

This is good for scheduling things like exporting a copy of your VDS config on a regular basis, etc.


################################
#
# PowerCLI script with list of vCenter servers
# Created by BLiebowitz on 11/11/2015
#
################################

# Build array for each vCenter
$array = "vcenter1", "vcenter2", "vcenter3", "vcenter4"
for($count=0;$count -lt $array.length; $count++)

{
# Connect to vCenter
connect-viserver $array[$count]

# perform the work you wanted to perform.  use the $array[$count] variable for the vCenter server name. (including the brackets)

}

Hope you find this useful!

Ben Liebowitz, VCP, vExpert
NJ VMUG Leader

Share This:

2 thoughts on “Display list of Multiple vCenter Servers to connect to in your PowerCLI Scripts

  1. So, I can do this instead?

    switch ($Ivcenter)
    {
    1 {“vCenter1”}
    2 {“vCenter2”}
    3 {“vCenter3”}
    4 {“vCenter4”}
    }

    Can I leave out the “default” line?

    Thanks, appreciate the suggestion!

    – Ben

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.