Mount/unmount an ISO (VHD) file in a Windows 10/11 cmd script

Discussion in 'Scripting' started by rpo, Feb 2, 2023.

  1. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    Prerequisite : Powershell store cmdlet
    Input parameter : the variable img contains the full path to the ISO(VHD) file
    Output parameter : iso contains the drive letter: of the mounted image on a virtual drive

    Mount an ISO(VHD) file :
    Code:
    for /f "usebackq" %%? in (`powershell "(Mount-DiskImage -ImagePath '%img%' -PassThru|Get-Volume).DriveLetter"`) do set "iso=%%?:"
    
    Unmount the ISO(VHD) file :
    Code:
    powershell DisMount-DiskImage -ImagePath '%img%' >nul
    Admin is required for VHD files

    Here is an example of a cmd script; adapt to your needs.
    The scripts proposes the use of subroutines.
    Code:
    @echo off
    rem set /p img="Enter the full path of the ISO image : "
    set "img=c:\cd-rom\windows 11\22621.1194.230121-0244.NI_RELEASE_SVC_PROD3_CLIENTMULTI_X64FRE_FR-FR_FIXED_2023_01_28.ISO"
    
    echo;&echo *** One-liner code  to mount an ISO ***&echo;
    for /f "usebackq" %%? in (`powershell "(Mount-DiskImage -ImagePath '%img%' -PassThru|Get-Volume).DriveLetter"`) do set "iso=%%?:"
    Echo Mounted ISO drive letter : %iso%&timeout 3 >nul
    echo *** One-liner code  to unmount an ISO ***
    powershell DisMount-DiskImage -ImagePath '%img%' >nul&timeout 3 >nul
    
    echo;&echo *** Mount an ISO using a subroutine ***&echo;
    call :mount_iso "%img%" iso
    Echo Mounted ISO drive letter : %iso%&timeout 3 >nul
    echo *** Unmount an ISO using a subroutine ***
    call :unmount_iso "%img%" &timeout 3 >nul
    goto :term
    rem
    :mount_iso
    for /f "usebackq" %%? in (`powershell "(Mount-DiskImage -ImagePath '%1' -PassThru|Get-Volume).DriveLetter"`) do set "%~2=%%?:"
    exit /b
    rem
    :unmount_iso
    powershell DisMount-DiskImage -ImagePath '%1' >nul
    exit /b
    rem
    :term
    echo;&echo End of demo&pause