20.02.2024
В Windows можно монтировать файлы виртуальных жестких дисков в VHD и VHDX формате прямо из консоли управления дисками (Disk Management). Администратор Windows может смонтировать VHD/VHDX файл в проводнике и назначить ему букву диска. Однако при каждой перезагрузке Windows такие виртуальны диски приходится монтировать вручную.
В этой статье, мы настроим задание автоматического монтирования VHD/VHDX дисков при загрузке Windows.
- Откройте консоль управления заданиями планировщика Windows (
Taskschd.msc
) - Создайте новое задание (Create Basic Task);
- Укажите имя задание
AutoMount_MyData_VHDX_G
; - В качестве триггера выберите When the computer starts;
- Action ->
Start a program
;Program/script:
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
Add argument:
-command "Mount-DiskImage -ImagePath C:\mydata.vhdx –PassThru | Get-Disk | Get-Partition | Set-Partition -NewDriveLetter G "
- Откройте свойства задание у укажите, что оно должно запускаться от имени NT AUTHORITY\SYSTEM (Change User or group ->
SYSTEM
). - Перезагрузите компьютер и проверьте, что VHDX диск монтируется автоматически.
Если вы хотите смонтировать VHDX не в отдельный диск, а в папку, измените код PowerShell команды следующим образом:
Mount-DiskImage -ImagePath C:\mydata.vhdx –PassThru | Get-Disk | Get-Partition | Add-PartitionAccessPath -AccessPath "C:\Folder01"
В Windows 8 Microsoft упростила работу с файлами образов ISO, если раньше для монтирования в ISO-образов в Проводнике необходимо было устанавливать сторонние программы, то теперь достаточно просто кликнуть по образу два раза мышкой. А вот с образами VHD и VHDX это не пройдет, смонтировать их можно только из оснастки управления дисками, а ведь они являются для Windows родными, поддерживаемыми ею из коробки.
Но можно пойти другим путем — добавить образа VHD и VHDX в «автозагрузку», то есть сделать так, чтобы они монтировались при загрузке системы.
Что такое файлы VHD и VHDX
Если кто не в курсе, VHD и VHDX — это файлы виртуальных дисков, при монтировании которых в «Этом компьютере» появляется новый раздел. Каждый такой раздел может иметь собственную файловую систему и содержать любые файлы, но по сути он сам является файлом-контейнером. Форматы VHD и VHDX поддерживаются не только Windows, но также приложениями для работы с образами и виртуальными машинами. VHDX — более новая версия образа, в отличие от VHD, контейнеры этого типа имеют большую емкость, также ими поддерживается защита от повреждения данных при сбоях питания.
Автомонтирование VHD и VHDX
Реализовать этот нехитрый трюк вам помогут встроенный планировщик заданий и PowerShell.
Откройте планировщик командой taskschd.msc, выберите опцию «Создать задачу».
Дайте заданию подходящее имя и отметьте опции как показано на втором скриншоте.
Затем переключитесь на вкладку «Триггеры», нажмите «Создать».
В меню в верхнем выпадающем списке «Начать задачу» выберите опцию «При запуске» и нажмите «OK».
Перейдите на вкладку «Действие», нажмите «Создать».
В качестве скрипта или программы укажите powershell.exe, а в качестве аргумента команду Mount-VHD -Path «полный путь к образу VHD или VHDX».
Сохранив настройки, перейдите на вкладку «Условия» и отключите выполнение задания только при питании от электросети.
Если потребуется, введите пароль от учетной записи администратора.
Сохраните все настройки и перезагрузитесь.
Указанный диск должен смонтировать автоматически. Исключение составляют новые виртуальные диски с нераспределенным дисковым пространством, их нужно будет инициализировать в оснастке управления дисками вручную.
Через планировщик и с админскими правами
Прежде всего нужно создать в любом месте системы командный файл для каждого подключаемого VHD-диска. Это может быть обычный текстовый документ. Пишем а него такие вот строки:
select vdisk file="D:\VHD\work.vhd" attach vdisk assign letter=W
В примере указаны мой путь к файлу VHD и имя назначаемой этому диску буквы, у вас же будет иначе.
На клавиатуре нажимаем Win+R и в открывшемся окне вводим taskschd.msc, после чего жмем Enter — откроется панель управления планировщиком.
Далее нужно добавить новую задачу (в колонке справа — Создать задачу).
Текстовый вариант
Общие
Имя — произвольное значение
Учетная запись — указывайте админа системы
Выбираем «Выполнять для всех пользователей»
Выбираем «Выполнить с наивысшими правами»
В селекторе «Настроить для» — «Windows 10»
Триггеры (создаем новый)
В селекторе «Начать задачу» — «При запуске»
Действия (создаем новое)
Действие — «Запуск программы»
Программа или сценарий — diskpart
Добавить аргументы — /s «%путь_до_командного_файла%«
Условия
Снимаем флажок «Запускать только при питании от сети»
Жмем OK внизу окна и вводим пароль от учетки адиминистратора.
Вариант со скринами
Все то же самое, что выше, только в картинках. Все, что следует изменить — отмечено желтым маркером. Если что-то не понятно — текстовое описание в помощь.
После перезагрузки диск(и) автоматически подцепятся к системе.
Skip to content
How to Automatically Mount VHD or VHDX File on Startup in Windows 10
Windows 10 supports virtual drives natively. It is able to recognize and use ISO, VHD and VHDX files. For ISO files, Windows 10 creates a virtual disk drive. For VHD and VHDX files, Windows 10 creates a new drive accessible via the This PC folder in File Explorer. Also, these files can be used in Hyper-V machines. You might be interested in mounting a VHD(X) file automatically on startup. Here’s how it can be done.
What are VHD and VHDX files
The Virtual Hard Disk (VHD) file format allows encapsulation of the hard disk into an individual file for use by the operating system as a virtual disk in all the same ways physical hard disks are used. These virtual disks are capable of hosting native file systems (NTFS, FAT, exFAT, and UDFS) while supporting standard disk and file operations. The maximum size of a VHD file is 2,040 GB.
VHDX is a new version of the VHD format which has a much larger storage capacity than the older VHD format. It also provides data corruption protection during power failures and optimizes structural alignments of dynamic and differencing disks to prevent performance degradation on new, large-sector physical disks. It supports for virtual hard disk storage capacity of up to 64 TB.
Virtual disk types
Windows 10 supports two virtual disk types:
- Fixed—The VHD image file is pre-allocated on the backing store for the maximum size requested.
- Expandable—Also known as «dynamic», «dynamically expandable», and «sparse», the VHD image file uses only as much space on the backing store as needed to store the actual data the virtual disk currently contains. When creating this type of virtual disk, the VHD API does not test for free space on the physical disk based on the maximum size requested, therefore it is possible to successfully create a dynamic virtual disk with a maximum size larger than the available physical disk free space.
There are number of methods you can use to create a VHD file. I’ve reviewed them all in the following blog post: Create a New VHD or VHDX File in Windows 10.
Note: This method utilizes PowerShell commands which work only when the Hyper-V feature is enabled. You need to activate Hyper-V on your PC to proceed.
- Open Administrative Tools.
- Click the Task Scheduler icon.
- In the Task Scheduler library, click on the Create Task… link on the right.
- In Create Task dialog, fill in the Name box some meaningful text like «Automount of my VHD Drive».
- Set the options as follows:
— Configure for Windows 10.
— Run whether user is logged on or not
— Run with highest privileges box - Switch to the Triggers tab and click on the New… button.
- Set the Begin the task option to At startup.
- Select to the Actions tab, and click on the New button.
- In the Program/script text box type
powershell.exe
. - Type the following in the Add arguments text box:
Mount-VHD -Path "Full\path\to\your\VHD or VHDX\file"
. Change theFull\path\to\your\VHD or VHDX\file
portion to the actual full path of the VHD/VHDX file you want to have automatically mounted at startup. - Switch to the Conditions tab and disable the option Start the task only if the computer is on AC power.
- Click on the OK button to create the task.
- Type your user account password (or other administrative user account credentials).
You are done!
Notes:
That’s it.
Support us
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!
Read time 5 minutes
Computers with Windows 10 and Windows 8.1 can be mounted with a virtual hard disk (VHDX or VHD) with a .vhdx or .vhd file extension. The virtual hard disks function like a physical hard drive completely. In normal words, VHD is just a file that is stored on a real disk drive of your computer which is useful in storing any type of data.
The major disadvantage of VHD or VHDX drives is that you need to mount them every time you reboot your Windows PC. Furthermore, the normal users always depend on the local computer administrators to mount a virtual disk file as admins are authorized to do so. Hence the best-suggested way for users of Windows 10 and Windows 8.1 is setting VHD/VHDX files to mount at startup as they are incorporated with the ability to auto-mount VHD/VHDX files whenever you reboot windows.
How to Auto-Mount a VHD/VHDX file at startup in windows 10 and 8.1?
There are multiple methods that can be used to setup VHD/VHDX files in Windows system to automatically mount virtual hard disk files at the time of Windows startup. We have mentioned the best manual method to make it hassle-free for you.
Auto-Mount VHD/VHDX using computer management for windows 10 and 8.1:
Step 1: Open VHD/VHDX file location and create a text file with the following code:
select vdisk file=”C:\Users\poojac\Documents\Outlook Files\Auto-Mount.vhd”
attach vdisk
select part 1
assign letter=R
exit
Please note: The script is helpful for mounting the VHD/VHDX file, partition selection and assigning a letter to the specified drive.
Step 2: Press Windows + X keys from your keyboard and select Computer Management.
Step 3: Under System Tools, right-click on Task Scheduler and select Create Task
OR
You can simply select Create Task under Actions from the right-pane.
Step 4: Do the following for different tabs in the Create Task window.
Under general tab,
- Type the Name of the task.
- Type in a Description for a better understanding of the task in detail.
- Select Run whether the user is logged on or not and Run with highest privileges.
Under triggers tab:
- Select the New button to set up a New Trigger.
- Select At Startup for Begin the task.
- Under Advanced Settings choose delay task for (time).
Under Actions Tab:
- Create a new action by clicking on the New button
- Select Action as Start a program, select the Program/Script and in the Add arguments(optional) enter:
/s (followed by space) and enter the complete path and name of the script file (the text file created in step 4).
Under Conditions Tab:
- Uncheck the Stop if the computer switches to battery power.
- Uncheck Start the task only if the computer is on AC power.
- Click OK to create the task.
Step 5: Exit Computer Management and restart your computer to test the auto-mount method.
At the End:
The method works successfully for all VHD or VHDX files present on your computer or you have created a new one. But, in case any of this VHD file is corrupted or damaged then you will fail to auto-mount it. Therefore, to get rid of the VHD corruption and damage you can try a professional solution specially designed for recovery of VHD files known as Kernel for VHD Recovery software. The intelligent application works flawlessly to repair and restore complete data of VHD/VHDX files within in no time.