Monday, February 24, 2014

PowerShell to seach Hyper-V VM Hard Disks for a specific VHD/VHDX file path

Sometimes people may not always place the VHD/VHDX files in the path your expecting them to be which if this is on a different partition it could cause some administrative overhead when managing the disk space on your host server. I was faced with this problem and came up with the following little PowerShell script to help search all VMs for an attached disk with the path of the VHD file I found.

$VHDToFind = Read-Host "Enter the Full Path to the VHD that you want to search for?"
Get-VM | ForEach-Object {$vmHDD = Get-VMHardDiskDrive -VMName $_.Name; if ($vmHDD.Path -EQ $VHDToFind) {Write-Host "VHD attached to $($vmHDD.VMName)" -ForegroundColor Green;}}