Getting vCenter info for a VM using powershell

DuckStalker picture DuckStalker · Oct 24, 2014 · Viewed 7.1k times · Source

I need to get VMs' vCenter information, or at least just the vCenter name,

I've looked online at vmware help and all they have is connect to the vCenter to get the VM info, exactly the opposite of what i'm trying to achieve. Is it even possible ? giving I have the machine fqdn and ipaddress ?

Thanks

Answer

omrsafetyo picture omrsafetyo · Mar 16, 2017

The vCenter name sits in the Uid of each object. For a VM, you can try the following snippet:

$vm.Uid.Substring($vm.Uid.IndexOf('@')+1).Split(":")[0]

Or:

Get-VM | % {
  [PSCustomObject] @{
    Name = $_.Name
    vCenter = $_.Uid.Substring($_.Uid.IndexOf('@')+1).Split(":")[0]
  }
}

So this loops through every VM in your connected vCenters, and gets the VM Name, and then pulls the vCenter from the Uid. The format of the Uid appears to be:

/VIServer=[username]@[vCenter]:[port]/VirtualMachine=[VirtualMachineID]

So it starts grabbing the vCenter name at the index of '@' + 1, and then splits the resulting string on a colon (the point before the port) and grabs the first item in that resulting array. This can be done slightly more gracefully with regex:

[regex]::Match($vm.Uid,'.*@(.*):').Captures.Groups[1].Value