PowerShell, Quick Tips, Scripting, wmi, WQL
comment 1

PowerShell Quick Tip: Finding the drive letter of a mounted VHD

I have been working on a few scripts to automate Hyper-V VM deployment. One of the tasks in this framework is to take a pre-configured VHD, mount it, and prepare it for deployment steps. I have been using diskpart scripting to mount VHDs as some of these scripts will be used on a non Hyper-V system too. On a non-Hyper-V system, the WMI interfaces (in root\virtualization) to mount VHDs won’t be available. The biggest challenge when using diskpart to mount a VHD was to find the drive letter that got assigned to the newly mounted VHD.

This can be solved multiple ways using PowerShell. In today’s post, I will show how this can be done using WMI eventing. Check the following code:

Using this function, when we mount a VHD, an event is triggered for the newly added drive. This triggers setting a global variable called $drvLetter. The same will be returned to the calling script. This is it!

As I mentioned, there is more than one way to achieve this using PowerShell. In fact, there is a one-liner without using WMI eventing at all. I will save this for next year! 🙂

Wish you all a very happy and prosperous new year!

Filed under: PowerShell, Quick Tips, Scripting, wmi, WQL


Ravikanth is a principal engineer and the lead architect for Microsoft and VMware virtualized and hybrid cloud solutions within the Infrastructure Solutions Group at Dell EMC. He is a multi-year recipient of Microsoft Most Valuable Professional (MVP) award in Windows PowerShell (CDM) and Microsoft Azure. Ravikanth is the author of Windows PowerShell Desired State Configuration Revealed (Apress) and leads Bangalore PowerShell and Bangalore IT Pro user groups. He can be seen speaking regularly at local user group events and conferences in India and abroad.