In today’s post I am going to share a small script block I used long back. I wanted to get VMware ESXi Host and Cluster name for a Virtual Machine from vCenter. Not necessarily the Host will remain same if I check it again after few hours. However, I just wanted to get that information at a particular time. For fewer VMs you can quickly get it from the vCenter directly. If you have hundreds of VM you will definitely need a script!
First, we will take the list of VMs, vCenter Name and an Output file path as input. You can set those as parameters too.
$iFile = "<Some Path>\serverlist.txt" # Input file containing list of VMs
$oFile = "<Some Path>\VM-Host-Cluster-Details.csv" # Output file to store VM, ESXi Host and Cluster Name
$vCenterName = "myvCenter.<somedomain.com>" # vCenter name to connect
Now, check if provided input file exists at the provided path.If not, exit. Otherwise, connect to the vCenter and loop through each VM Name, check and collect ESXi Host and Cluster name.Finally, write those information into a csv output file. However, before we connect vCenter, we will import the Powershell module for VMware.VimAutomation.Core.
if(!Test-Path $iFile){
Write-Output "No input file provided. Please check and try again!"
Exit
}
else{
if(Test-Path $oFile){
Remove-Item -Path $oFile -Force
}
"VM Name, Host Name, Cluster Name" | Out-File $oFile -Append -Encoding ASCII
Import-Module VMware.VimAutomation.Core
Connect-VIServer $vCenterName
ForEach($srv in Get-Content $iFile){
$vm = $vHost = $vCluster = ""
$vm = Get-View -ViewType VirtualMachine -Filter @{"Name" = $srv}
$vHost = & {$vm.UpdateViewData("Runtime.Host.Name"); $vm.Runtime.LinkedView.Host.Name}
$vCluster = (get-view (get-view -ViewType HostSystem -Filter @{"Name" = $vhost}).parent).name
"$srv,$vHost,$vCluster" | Out-file $oFile -Append -Encoding ASCII
}
}
disconnect-viserver $vCenterName
Once the script runs successfully, you will receive an output file with information mentioned above.