Hyper-V, Resources, Scripting, Virtualization, Windows
comments 3

Script to mark mounted VHD as online disk

Updated scripts are here http://139.59.40.198/blog/?p=241

In a previous post, I wrote a script to mount/unmount a Hyper-V VHD from command-line as well as right-click context menu. However, on Windows Server 2008 & Vista systems, the mounted VHD will be kept offline. You will have to mark it online from disk management MMC or using diskpart. Glenn asked about an automated means of marking the disk online after mounting it. I remember writing something like that using diskpart and never posted it online. With that background, here is the script to do that job. You may call it from the same VBScript using WshShell.Run method.

@echo off

::::::::::::::::::::::::::::::::::::::
:: Wait a bit before VDS restarts
::::::::::::::::::::::::::::::::::::::

echo WScript.Sleep(5000) > %temp%\sleep.vbs
cscript.exe %temp%\sleep.vbs

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Build a temp diskpart script to get offline disk details
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

echo list disk > %temp%\listdisk.dps
FOR /F “tokens=1,2,3” %%i IN (‘diskpart /s %temp%\listdisk.dps’) DO @IF %%k == offline SET VHDDISK=%%i %%j
echo VHD Disk is: %VHDDISK%

:::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Build a temp diskpart script to make the VHD online
:::::::::::::::::::::::::::::::::::::::::::::::::::::::

echo select %VHDDISK% > %temp%\vhdonline.dps
echo online >> %temp%\vhdonline.dps
echo exit >> %temp%\vhdonline.dps

::::::::::::::::::::::::::::::::::::::::::::::
:: Run the diskpart script to make VHD online
::::::::::::::::::::::::::::::::::::::::::::::

cscript.exe %temp%\sleep.vbs
diskpart /s %temp%\vhdonline.dps

::::::::::::::::::::::::::::::::::::::::::::::
:: Show if the VHD is set online or not
::::::::::::::::::::::::::::::::::::::::::::::

cscript.exe %temp%\sleep.vbs
diskpart /s %temp%\listdisk.dps

::::::::::::::::::::::::::::::::::::::::::::::
:: Delete all temp files created
::::::::::::::::::::::::::::::::::::::::::::::

del %temp%\listdisk.dps
del %temp%\vhdonline.dps
del %temp%\sleep.vbs

Filed under: Hyper-V, Resources, Scripting, Virtualization, Windows

by

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.