Finding the drive letter of the most recently mounted xvhd or vhd file in batch?

Solution 1:

Finding the drive letter of the most recently mounted xvhd or vhd file in batch? How do I find out what drive letter it was assigned using the command prompt?

Pipe the output of Get-DiskImage to Get-Volume or Get-Disk and Get-Partition:

For an ISO file:

GET-DISKIMAGE filename.iso | GET-VOLUME

For a VHD file:

GET-DISKIMAGE filename.vhd | GET-DISK | GET-PARTITION

Source


Example

Based on the article you provided I incorporated the PowerShell logic into the below batch script to include dynamically getting the drive letter used to mount the VHD or ISO file so you can then use that as a variable name to CD to the directory to run your command implicitly or you can use it otherwise to explicitly set the drive letter for whatever you need it for the commands you'll use it with, etc.

Script

@ECHO OFF

SETLOCAL

SET DiskPartScript="%TEMP%DiskpartScript.txt"

ECHO SELECT VDISK FILE="%~1" > %DiskPartScript% 
ECHO ATTACH VDISK >> %DiskPartScript%

DiskPart /s %DiskPartScript%

SET PowershellScript="%TEMP%\PowerShellScript.ps1"

:: -- Use below for VHD 
ECHO GET-DISKIMAGE "%~1" | GET-DISK | GET-PARTITION | Select -ExpandProperty DriveLetter > "%PowershellScript%" 

:: -- Use below for ISO 
::ECHO GET-DISKIMAGE "%~1" | get-VOLUME | Select -ExpandProperty DriveLetter > "%PowershellScript%"

SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0 
CD /D "%PowerShellDir%" 
FOR /F "DELIMS=" %%A IN ('Powershell -ExecutionPolicy Bypass -Command "& '%PowershellScript%'"') DO SET "DriveLetter=%%A"

CD /D "%DriveLetter%:\" 
<Commands> 
<Commands>

ENDLOCAL

Further Resources

  • Get-DiskImage
  • Get-Disk
  • Get-Partition