The problem after a restart

If you have played with the new VHD feature in windows 7 or windows 2008 then you know just how cool of a feature this is. However the problem is that when you reboot your machine you find that when it comes back up all your VHD files are no longer attached? Here is what I did to get around the issue.

Configure a startup task to attach a VHD

  1. Create a batch file that will hold the following line:

    diskpart /s "c:\path to script\diskpartscript.txt"

    I named my batch file attachvhd.bat and placed it in the same folder as my VHD files.

    Batch file that launches DiskPart to attach a virtual hard disk

  2. Create the script file that is being referenced by the attachvhd.bat batch file. Here is what the contents of that script needs to contain:

     select vdisk file="c:\path to vhd files\myvhddrive.vhd"
     attach vdisk
    

    I named my script file diskpartscript.txt and placed it in the same folder as my VHD files.

    DiskPart script used to attach a virtual hard disk

  3. Create a scheduled task that will automatically run when your machine starts up.

    • Go to Start / Administrative Tools / Task Scheduler

    • Click Create Basic Task

      Create Basic Task option in Windows Task Scheduler

    • Fill in the name of the task and the description and Click Next

      Windows Task Scheduler task name and description wizard

    • Select “Start a program” radio button option and then Click Next

      Task Scheduler option to start a program

    • Select “When the computer starts” and then Click Next

      Task Scheduler trigger to run when the computer starts

    • Browse to the folder that you setup your batch file in and select it. Click Next

      Task Scheduler selecting the attachvhd batch file

    • Click Finish

      Task Scheduler summary before finishing the VHD task

  4. You have now completed all the necessary steps. Restart your computer and you should find that your VHD files are now automatically attached. One caveat is that if you reboot and you log into your machine quick enough it is possible that the task may not have been run yet. Once you are logged in if the task runs you will get an Autoplay dialog as follows. Simply close it. This does not happen if the task runs before you get logged in.

    Windows AutoPlay notification after attaching the virtual hard disk

Notes for newer Windows installations

This walkthrough documents a 2009 Windows 7 / Windows Server 2008 configuration. Windows still documents the select vdisk and attach vdisk DiskPart commands, but the Task Scheduler interface, startup permissions, and disk formats may differ on newer releases. Verify the target disk path before attaching it, protect any startup script against unauthorized edits, and configure the scheduled task with only the permissions needed for the operation. Microsoft also documents Task Scheduler run levels.