Automation in Action: Which Hosts are Accessing a Given Datastore?

One of the biggest challenges in a new environment can be mapping out resources. In a large environment you may encounter ESXi hosts that were moved between clusters, datastores that were mapped to multiple unnecessary hosts, or any number of additional surprises or inconsistencies. I encountered such a challenge and needed to answer a seemingly simple question: Which hosts and which clusters would be impacted by a loss of a datastore?

Not knowing exactly how I wanted to tackle the task I started digging through vSphere Client manually. I looked at the datastore, listed out the hosts on the Hosts tab, then searched for those hosts and wrote out the clusters. This was tedious and repetitive but I figured out the format in which I should present the data. Time to script!

I wanted to be prompted to enter a datastore name and have the identifier returned. I also wanted it to gather all of the hosts accessing the datastore, the clusters those hosts were in, and output that to a CSV. I have also thrown in some Quality of Life improvements suggested by coworkers. The script detects if you’re already connected to vCenter and prompts you to connect if not and it outputs the file name and path once the script is complete. I use Powershell ISE to script but it works fine in PowerGUI or a traditional black box PowerCLI session.

Add-PSSnapin VMware.VimAutomation.Core

#Check status of vCenter server and connect if disconnected
if($global:DefaultVIServer.IsConnected){
Write-Host "Connected to vCenter"
}else{
Connect-VIServer (Read-Host "Enter vCenter Server")}

#prompt for Datastore to investigate
$ds = Get-Datastore (Read-Host "Enter Datastore")

#Get Disk Identifier for a given Datastore Name#
$ds.ExtensionData.Info.Vmfs.Extent.DiskName

#Get Hosts accessing Datastore and output to a CSV File# $ds.ExtensionData.Host.Key | Get-VIObjectByVIView | Select Name, @{N=”Cluster”;E={Get-Cluster -VMHost $_}}| Export-CSV $ds-Hosts.csv
$Filepath = Get-Location
Write-Host File $ds-Hosts.csv written to $Filepath.Path

For future improvement I would like to have the LUN Identifier output into the CSV. Other than that I am very happy with the script. The seemingly simple question pushed me to the limits of my ability to script and/or search for code hints. It was very rewarding and an hour well spent.

I have shared this script on GitHub. If you have any suggestions for improving the script please let me know.