How To Properly Get The Drive Letter of a Mounted VHD in script. Is it possible?

list volume
select volume <volume_number_of_attached_VHD>
assign letter=v

in this part of script it's need to specify the number of volume, which can be different from time to time.

Also, if it is not impossible, I have an idea to put some label to that virtual volume in early stage and then, in later stage determine the number of volume searching the drive with that label. Can this idea be implemented?



Just in case you still care, I wanted to post this somewhere on the internet as I just figured this out and haven't seen anyone else answer this question before.

This finds the DVD-ROM and assigns the letter v.

for /F "tokens=2" %%i in ('%comspec% /c echo list vol ^| diskpart ^| find "DVD-ROM"') do %comspec% /c echo select vol %%i ^& echo assign letter=v|diskpart

|improve this answer|||||

Just trying to undestand and explain what is going on in the geek's reply to my question.

for ... in () do ... is a loop construction

/F switch - is loop through text, on tokens=n - Specifies which numbered items to read from each line (default = 1) To make it simple : taking the n-th column of the raw string, delimited by delimiter (a space symbol by default)

More about for /F : https://ss64.com/nt/for_f.html

%comspec% - if I am not mistaken is just a name of command line interpreter - 'cmd' in most cases

I suspect that ^| and ^& - is kind of piping... or consequent execution with correspondence || and && in linux. correct me if I am wrong...

Sorry, do not have windows at hand no chance to check, but accepting an answer in advance as other members find it usefull.

|improve this answer|||||
  • | is for piping & is for combining commands ^ is an escape character || and && do work in command line as well and are quite useful =) – geek_01 Jun 13 '19 at 17:37

Given the age of this question, it is (now) strongly suggested to use Powershell to do these operations.
But since OP insist using CMD, you'd have to run the appropriate call to Powershell from CMD.

The way to do that is:

PowerShell -Command "(Get-DiskImage -ImagePath "C:\VHD\xxx.vhdx" | Get-Disk | Get-Partition | Get-Volume).DriveLetter"

For a WSL friendly version, substitute the \ with \\. And remember to have the powershell.exe in your PATH.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.