Wednesday, March 15, 2017

Quickly find where your VCenter VM is running using PowerShell and PowerCLI

VCenter is the glue to a solid VSphere environment, so if it stops working so do other components like Vmotion and DRS (pretty important). Most environments run Vcenter on a VM within VSphere, not a physical box. So, if Vcenter stops working to the point where it cannot be accessed via the web client, Windows client, or PowerShell, you will probably want to access the VM console to troubleshoot. Chances are though, you do not keep tabs on what ESXi host the Vcenter VM is running on. If you have more than a few ESXi hosts in your environment, trying to find which host the VCenter VM is running on can be painful if done manually. So instead of going through that hassle, lets automate that.

To do this lets use PowerShell and PowerCLI to build a small, simple function to access each ESXi host to see if the VCenter VM is running.

The flow of the function is fairly simple:
  • Connect to the ESXi host
  • Attempt to find the VCenter VM by name
  • If the VCenter VM is found, it writes the ESXi host to output
  • If it does not find VCenter, move on to the next ESXi host
In order to find VCenter I created a small PowerShell function below, but lets step through some of the commands this function uses.

Connect-VIServer is used to connect to VCenter or a ESXi host via a credential. Note this function assumes you have the same password on each ESXi host.

Connect-VIServer -Server $item -credential $RootCredential -ErrorAction stop

Next, Get-VM is used to find the VCenter VM on an ESXi host. It uses the $item variable which contains the current ESXi host in the foreach loop. If found, it writes the name of the VCenter VM and the vmhost to output.

 Get-VM -Name $item | select-object name,vmhost

Finally, after attempting Get-VM, we disconnect from the current ESXi host we are connected to with Disconnect-ViServer.

Disconnect-viserver -force -confirm:$false

Now lets use the function!

We will create a $hosts variable with the hostnames of our ESXi hosts, use Get-Credential for our ESXi username and password (likely root), and then use the Get-VCenterEsxiHost function to find our VCenter VM.

Looks like our VCenter is running on host1.

$hosts = @("host1","host2","host3")
$Credential = Get-Credential

Get-VCenterEsxiHost -VCenterVMName 'vcenterhost' -ESXiHosts @("host1","host2","host3") -RootCredential $Credential

  Name        VMHost
  ----        ------
  vcenterhost host1

There we have it. A very simple PowerShell function to find our VCenter.

No comments:

Post a Comment

Recompiling Chocolatey packages

Chocolatey is a very popular tool among system administrators as it helps automate package management for Windows. Since Chocolatey can be u...