Techibee.com

Get ESX host name from VM using PowerCLI

How to get ESX Host name of a guest VM using VMware PowerCLI? I came across this question in “Hyderabad PowerShell User Group” FB Group where I participate. Let us see how to achieve this using VMware PowerCLI.

There are various ways to query information of your VMware infrastructure but out of them PowerCLI is more efficient and recommended way.

To query any information from VMware infrastructure, first we need to connect to Virtual Center(VC) from the PowerCLI console. You can download it from VMware official website.

The first thing we need to do after installing and launching PowerCLI console is, connecting to the VC. The PowerCLI talks directly with the VC API and for that it needs to establish a connection. To do that you can use the below command.

Connect-VIserver -Server "VCSERVER1"

After Connection, let us get a object of VM for which you want to know ESX Host name.

$VMName = Get-VM -Name "myvmpc1"

Get-VM is a cmdlet that queries the VC for given VM name and returns the VM object. This object We are storing in $VMName variable.

Now you can get the ESX host name by using VMHost property of the VM Object.

Write-Host "ESX Host name is $($VMName.VMHost)"

or you can get this by using another cmdlet called Get-VMHost to which you have to pass the VM object.

Get-VMHost -VM $VMName

Below is a small function which takes multiple VM names as input and saves the VM name and respective ESX host name in CSV file.

function Get-VMESXName {            
[cmdletbinding()]            
param(            
[string()]$VMName            
)            

foreach($VM in $VMName){            
$VMObj = Get-VM -name $VM            
"{0} : {1}" -f $VM, $VMObj.VMHost | Out-File c:\temp\VMESXInfo.csv -append            

}            

}

Happy learning…

Exit mobile version