PowerShell script to get VMs and their datastores from an offline VMware ESXi host via vCenter

I recently had the local storage controller fail in one of my ESXi hosts. The host carried on running, and the VMs on it carried on running, but it wasn’t very happy. It was unresponsive via the vSphere client, and there was a good chance that it wouldn’t boot up once it was shutdown. I wasn’t able to vMotion the VMs off it – they’d get part way through and then fail after a while.

My recovery plan was as follows: Shut down all the VMs running on the failing host, remove the host (and thus all its VMs) from vSphere, browse to the VMs on their various datastores and re-add them onto the remaining hosts by double-clicking their .vmx files.

Which was all fairly straightforward except that I still have a LOT of legacy SAN datastores, and the VMs could be on any of them. So I wrote this script to interrogate vCenter and tell me where the VMs live on a particular host. This script does not talk to the host, so will work even if it is powered off. You will need to have VMware PowerCLI installed.

Connect-VIServer -Server vcenter.rcmtech.co.uk
$VMs = Get-VM
# Note that the hostname here needs to be written exactly as the host appears in the vSphere client
$VMHost = Get-VMHost -Name deadhost.rcmtech.co.uk
foreach($VM in $VMs){
    if($VM.VMHost -like "deadhost*"){

Simple but effective – albeit slow, but PowerCLI seems to be painfully slow anyway.

This entry was posted in PowerShell, vSphere and tagged , , , , , , , , . Bookmark the permalink.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.