PowerCLI: Host and VM location script across many Vcenters

If a company has a very large environment with many vcenters it sometimes can be difficult to track down where a host my be located.  Then let’s say you need to know what VM’s and what hosts are running on top of it? For this script you do need a list of hosts that you want to find.  If you want to just find out all the information you could modify the script to make the hostlist to just be get-vmhost instead of from a file.

I wrote a small script that once connected to all your vcenters, you can pass a csv with a list of hostnames and it will pull the VM’s, their host, and which VC it is in back out into a CSV.  In the script we are using the VIProperty cmdlet which lets you make your own property for objects in vmware.

The CSV will need to have the header “hostname” and then the FQDN of the hosts below it.

#Ready host file name in
$hostlist = Read-Host "Enter server list name"
$hostlist = Import-Csv $hostlist

# Create Vcenter Location Property
New-VIProperty -Name vCenterServer -ObjectType VMHost -Value {$Args[0].Uid.Split(“:”)[0].Split(“@”)[1]} -Force | Out-Null

#Loop through the hostlist and create spreadsheet.  Write for any hosts that aren't found.
$hostlist | %{
    Write-Host "Starting" $_.hostname
    if (Get-VMHost $_.hostname -ErrorAction SilentlyContinue ) { 
    $vmhost = get-vmhost $_.hostname
    $vmhost| get-vm | select Name,VMHost,@{Name="Vcenter";Expression={($vmhost | select vcenterserver).vcenterserver}}
        Write-host "Failed to find" $_.hostname 
} | Export-Csv -NoTypeInformation vm_list.csv

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: