To verify if a VMDK in a datastore is attached to any virtual machine or template
search cancel

To verify if a VMDK in a datastore is attached to any virtual machine or template

book

Article ID: 408915

calendar_today

Updated On:

Products

VMware vSphere ESXi

Issue/Introduction

In some situations, it is necessary to verify whether a VMDK file stored in a datastore is currently in use by any virtual machine or template. This need often arises before performing operations such as cleanup, migration, or storage optimization. While tools like "vmfsfilelockinfo" or "vmkfstools -D" can help identify file locks, they are not always reliable for this purpose. For example, if the VMDK is used by a template or a powered-off virtual machine, these methods may show no active locks.

The most accurate way is to check the .vmx (for virtual machine) or .vmtx (for template) configuration files of all virtual machines and templates. However, this becomes more complicated when a virtual machine is powered on, because the .vmx is locked by the host running the VM, and other hosts cannot access its configuration details. This makes the verification process more challenging.

Environment

VMware vSphere 7, 8, and 9 environments with vCenter Server and ESXi hosts, managed through PowerCLI.

Resolution

The following PowerCLI script retrieves all virtual machines and templates along with their disk names (e.g., Hard disk 1, Hard disk 2, etc.) and corresponding datastore paths.

=======================================

$VC = "IP or FQDN of vCenter"
$VC_user = "User name, for example, [email protected]"
$VC_password = "Password of above user"

Connect-VIServer -Server $VC -User $VC_user -Password $VC_password

# To retrieve disk names and paths from all virtual machines
Get-VM | Get-HardDisk | Select `
    @{N="VM";E={$_.Parent.Name}}, `
    @{N="DiskName";E={$_.Name}}, `
    @{N="VMDK_Path";E={$_.Filename}} ` | ft -autosize

# To retrieve disk names and paths from all templates
Get-Template | Get-HardDisk | Select `
    @{N="Template";E={$_.Parent.Name}}, `
    @{N="DiskName";E={$_.Name}}, `
    @{N="VMDK_Path";E={$_.Filename}} ` | ft -autosize

Disconnect-VIServer -Server $VC -Confirm:$false

=======================================

Save the script as Get-VMDKUsage.ps1, run it in PowerShell, and redirect the output to Get-VMDKUsage.txt. Then, search the file for the path or file name of the VMDK to determine whether it is in use by a virtual machine or a template.

Example usage:

 

  • In Windows PowerShell
    .\Get-VMDKUsage.ps1 > Get-VMDKUsage.txt

  • In Linux (using PowerShell Core / pwsh)
    pwsh Get-VMDKUsage.ps1 > Get-VMDKUsage.txt

The output file can then be searched for the target VMDK name.

 

 

Attachments

Get-VMDKUsage_1756692074399.ps1 get_app