'Getting vCenter info for a VM using powershell
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
Solution 1:[1]
I see the last answer here is 5 years old, but just today I found a way that goes deeper into the object hierarchy without having to deal with strings and splitting. To me it's more like the PoSH way.
(Get-VMHost "MyESXHost").GetClient().config.Server
Here's another way that's less deep in the hierarchy but uses a simple split instead.
(Get-VMHost $ESX).GetClient().ServerUri.Split('@')[1]
On some site I found an example that uses splitting heavier like in the previous answers. I less like this way, especially if it is avoidable, I am for the approach: the simpler, the better, but it works too.
Get-VMHost "MyESXHost" | Select-Object Name,@{N="vCenter";E={$_.Uid.Split('@')[1].Split(':')[0]}}
So, in general, there are three properties (maybe more can be found) that give the same result. :
Uid # need splitting
GetClient().ServerUri # need light splitting
GetClient().config.Server # no splitting, only object properties
I am not going here to looping with ForEach, hope it is not a problem.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | omrsafetyo |
