PowerCLI: Find a VM Based on RDM’s LUN ID

Let’s say you have a LUN ID that you clearly know is a RDM. How do you determine what virtual machine is associated with that disk?

Recently, I was prepping a cluster for routine ESXi patching. As part of my preparation, I scanned the cluster for RDM disks first to ensure that they were set to Perennially Reserved = True. After doing the RDM scan, I found a cluster that had a single RDM disk, but didn’t know which VM it was associated with. Although VMware has a Knowledge Base article (KB2001823) on how to do find RDM’s and which VM’s they’re associated with, it looks like it will find all RDM’s and VM’s across the entire vCenter Server. Since I know the cluster, and I know the RDM LUN ID, I wanted to narrow down the results for my particular needs.

Karim Elatov has a nice blog post over at VirtuallyHyper that goes through a couple of different ways to filter down the results. His last two script examples were very close to what I was looking for. In the end, here’s the script I put together and used for my particular needs:

Update: I’ve added in an additional check that will report if the RDM’s LUN ID is not found to be attached to any VM’s in the cluster.

########################################
# Script: find-vm-based-on-rdm-lun-id.ps1
# Purpose: Find a VM Based on RDM LUN ID.
########################################

$cluster = "ClusterName"
$naa = "eui."
$vms = Get-Cluster $cluster | Get-VM
$count = 0
foreach ($vm in $vms) {
     foreach ($disk in ($vm | Get-HardDisk -DiskType "RawPhysical","RawVirtual")) {
          if ($disk.ScsiCanonicalName -eq "$naa") {
               Write-Host "----------------------------------------"
               Write-Host "VM Name:  " $disk.Parent.Name
               Write-Host "LUN ID:   " $disk.ScsiCanonicalName
               Write-Host "Disk Name:" $disk.Name
               Write-Host "Disk Type:" $disk.DiskType
               Write-Host `n
               $count = $count + 1
          }
     }
}
if ($count -eq 0) {
     Write-Host "----------------------------------------"
     Write-Host "Disk $naa is not attached to any VM's in the $cluster Cluster."
     Write-Host `n
}