How to boot windows from grub

I have Windows 10 HOME installed on my system. After I installed Windows 10 HOME, I installed Ubuntu 14.04 LTS on a separate partition so that I could dual boot. I removed Ubuntu 14.04 LTS by dele...

I have Windows 10 HOME installed on my system. After I installed Windows 10 HOME, I installed Ubuntu 14.04 LTS on a separate partition so that I could dual boot.

I removed Ubuntu 14.04 LTS by deleting the partition it was installed on. Now I am unable to start my system. At boot, my system stops at the Grub command line.

I want to boot to my Windows 10 installation which I haven’t removed from my system.

This is displayed at startup:

GNU GRUB version 2.02 beta2-9ubuntu1.3 <br> 
minimal BASH-like editing is supported.for the first word, TAB lists
possible commands completions.anywhere else TAB lists the possible device or file completion.
grub>

How can I boot my Windows partition from this grub command?

roaima's user avatar

roaima

98.7k14 gold badges125 silver badges238 bronze badges

asked Feb 1, 2016 at 13:01

ANKIT SAINI's user avatar

The following worked for me with a GPT partitioned disk.

insmod part_gpt
insmod chain
set root=(hd0,gpt1)
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
boot

Note that you can enter a command line from the grub boot menu and just type commands as above to test out different combinations.

You need to enter the id of the EFI boot partition (not the windows partition) for the set root= command.

In the command line grub mode ls will list the hard drive partitions, help lists available commands.

Once you have set the root correctly you can ls / to view files and directories to find the correct path to the windows boot manager if it is not in the default location.

answered Mar 9, 2018 at 21:46

79E09796's user avatar

79E0979679E09796

6405 silver badges4 bronze badges

4

Just enter the command exit. It should take you to another menu that makes you select the Windows bootloader.

Worked on Lenovo Y50

AdminBee's user avatar

AdminBee

20.8k17 gold badges47 silver badges69 bronze badges

answered Nov 7, 2017 at 18:44

adonayresom's user avatar

adonayresomadonayresom

6395 silver badges6 bronze badges

7

Guesing you have an UEFI device, the windows bootloader is still installed. You can select it back in UEFI setup menu under boot, where you will prbably have two options (GRUB and the old default as the second), delete the first one or switch the order.

answered Feb 5, 2016 at 9:00

Alko's user avatar

AlkoAlko

9121 gold badge7 silver badges17 bronze badges

1

This answer is for those with UEFI who have deleted the Ubuntu partitions before removing grub

You will be doing this from Windows 10. No bootable media required.

Where bootrec /fixmbr, bootsect /nt60 and the Ubuntu live with the boot-repair suggestions have failed, this has worked for me:

(This answer borrowed verbatim from here)

  1. Run a cmd.exe process with administrator privileges
  2. Run diskpart
  3. Type: list disk then sel disk X where X is the drive your boot files reside on
  4. Type list vol to see all partitions (volumes) on the disk
  5. Select the EFI volume by typing: sel vol Y where Y is the SYSTEM volume (this is almost always the EFI partition)
  6. For convenience, assign a drive letter by typing: assign letter=Z: where Z is a free (unused) drive letter
  7. Type exit to leave disk part
  8. While still in the cmd prompt, type: Z: and hit enter, where Z was the drive letter you just created.
  9. Type dir to list directories on this mounted EFI partition
  10. If you are in the right place, you should see a directory called EFI
  11. Type cd EFI and then dir to list the child directories inside EFI
  12. Type rmdir /S ubuntu to delete the ubuntu boot directory

Assuming you only ever had two operating systems (Win 10 & Ubuntu) you should now be able to boot directly to Windows without hitting the black grub screen.

Copied from https://askubuntu.com/questions/429610/uninstall-grub-and-use-windows-bootloader

G-Man Says 'Reinstate Monica''s user avatar

answered Sep 4, 2018 at 22:58

sa my's user avatar

sa mysa my

711 silver badge1 bronze badge

1

Just exit the grub by typing exit and go to bios setup and restore to default settings and restart the computer.

AdminBee's user avatar

AdminBee

20.8k17 gold badges47 silver badges69 bronze badges

answered Dec 8, 2018 at 7:01

phanindra tallam's user avatar

0

I recently bumped into the same problem. (i.e. originally have a a separate partition with Ubuntu installed, dual bootable from a grub menu. I then deleted that Ubuntu partition from Windows disk management, and when I rebooted, just the grub command menu).

What I did to get back to my Windows 10:

  1. Do a Ctrl + Alt + Delete to reboot. While rebooting, hold down the shift button.
  2. My PC then give me to option to press F12 for boot option. I clicked F12, and it gives me back a menu with Windows boot manager on it.
  3. I selected the Windows boot manager and click enter. I’m now back to Windows 10.

answered May 29, 2017 at 16:35

Atlas7's user avatar

Atlas7Atlas7

1113 bronze badges

This worked for me, now I have to find a way to permanently fix the mbr.

I recently bumped into the same problem. (i.e. originally have a a separate partition with Ubuntu installed, dual bootable from a grub menu. I then deleted that Ubuntu partition from Windows disk management, and when I rebooted, just the grub command menu).

What I did to get back to my Windows 10:

Do a Ctrl+Alt+Delete to reboot. While rebooting, hold down the shift button.
My PC then give me to option to press F12 for boot option. I clicked F12, and it gives me back a menu with Windows boot manager on it.
I selected the Windows boot manager and click enter. I’m now back to Windows 10.

Stephen Rauch's user avatar

answered Aug 26, 2017 at 19:18

John M. Marr's user avatar

Try this, its worked in my case:

grub> exit

You will get a list of operating systems installed. Select one.

answered Feb 21, 2020 at 4:37

ShaunT's user avatar

2

Try this:

rootnoverify (hd0,0)
chainloader +1
makeactive
boot

techraf's user avatar

techraf

5,64710 gold badges33 silver badges50 bronze badges

answered Nov 23, 2016 at 1:10

abhineet's user avatar

I have both Windows 10 and Ubuntu Desktop on separate partitions on a gpt disk.
Windows is trying to reboot to finish off its update but it’s causing me to be presented with the grub terminal prompt. I know i can boot ubuntu manually via linux vmlinuz-..., initrd init..., boot commands, but I can’t figure out how to do similar for Windows.

asked Oct 4, 2016 at 15:40

Alex Meuer's user avatar

5

In grub2 run the following commands one at a time

insmod ntfs
set root=(hdX,gptX)
chainloader (${root})/EFI/Microsoft/Boot/bootmgfw.efi
boot

Where hdX is the hard drive Windows is on (hd0 is the first drive) and gptX is the partition number of the Windows EFI partition, so if Windows was the very first partition on the first drive set root=(hd0,gpt0).

Source

answered Oct 4, 2016 at 16:34

Mark Kirby's user avatar

Mark KirbyMark Kirby

18k19 gold badges76 silver badges112 bronze badges

2

To update and add Windows to grub2:

sudo update-grub

Also, to always see the Grub2 menu, you can comment out the line

GRUB_HIDDEN_TIMEOUT=0

So it looks like

#GRUB_HIDDEN_TIMEOUT=0

in the file /etc/default/grub, and then run sudo update-grub again to make the change effective.

Zanna's user avatar

Zanna

68.2k55 gold badges209 silver badges319 bronze badges

answered Jun 18, 2018 at 23:27

Slavik Miroshnichenko's user avatar

Grub2 is a powerful boot loader and supports booting most operating systems. This article will guide you to boot Windows from Grub2 command line.

Although you can scan and boot into most of the operating systems installed on computers such as Windows, Linux, FreeBSD and macOS from the AIO Boot’s Grub2 menu. But Windows is a common operating system, AIO Boot v0.9.7.6 has added a menu to support booting into Windows faster without having to scan other operating systems (press i).

  • Grub2 command line
    • UEFI
    • Legacy
  • Add Grub2 menu

Of course we will use the menu instead of booting Windows from the Grub2 command line. But there are several reasons why you can not access the Grub2 menu. The most common reason is that you have accidentally deleted the partition that contains the Grub2 configuration file. Using the Grub2 command line is the only way before you have to use other rescue devices.

When you delete the partition containing Grub2 configuration file (grub.cfg) and its modules, Grub2 will stop in rescue mode. If the Grub2 modules are preloaded, you still have the opportunity to boot into Windows. Specifically, we need to load the ntldr module in Legacy BIOS mode and the chainloader module in UEFI mode. In my experience, on Ubuntu, Linux Mint, Debian, and other Linux operating systems, these modules are preloaded only when you boot in UEFI mode. This means that these modules have been embedded in the grubx64.efi file. AIO Boot is the same. But we should try anyway.

This is the Grub2 screen that stops in rescue mode.

grub rescue

error: no such device:
error: unknown filesystem.
Entering rescue mode...
grub rescue>

First, we will use the search command to find the partition containing the BCD file. This partition also contains the bootmgr or bootmgfw.efi file. Then we will load this file to boot into Windows.

UEFI

For UEFI, the BCD file will be located at /EFI/Microsoft/Boot/BCD on the EFI partition. This partition also contains the file /EFI/Microsoft/Boot/bootmgfw.efi. Use the chainloader command to chainload this file.

search -s root -f /EFI/Microsoft/Boot/BCD
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
boot

Legacy

For Windows Vista, Windows 7 to Windows 10, the BCD file will be located at /Boot/BCD. This partition also contains the file /bootmgr. Use the ntldr command to load this file.

search -s root -f /Boot/BCD
ntldr /bootmgr
boot

For Windows XP/2003, you will find the partition that contains /NTDETECT.COM and load the /ntldr file. You need to use the drivemap command to MAP the hard disk on which you installed Windows XP/2003 as the first hard disk if it is not.

search -s root -f /NTDETECT.COM
drivemap -s hd0 $root
ntldr /ntldr
boot

You will see the following errors if the corresponding modules are not preloaded as mentioned above.

Unknown command 'search'.
error: unknown filesystem.
Unknown command 'chainloader'.
Unknown command 'ntldr'.

If the files are not found on all partitions, you will see one of the following errors:

error: no such device: /EFI/Microsoft/Boot/BCD.
error: no such device: /Boot/BCD.
error: no such device: /NTDETECT.COM.

If you install Ubuntu or other Linux operating systems alongside Windows, then Windows will automatically be added to the Grub2 menu. If you install Grub2 manually, you can add Windows to the Grub2 menu manually. Here is the Grub2 script that I wrote for AIO Boot:

menuentry "Windows" {
	insmod regexp
	set saved_root=$root
	for dev in (*,*); do
	regexp -s device '((.*))' $dev
	if searchindevice "$device" ; then
		probe -s fstype -f $device
		if [ -z "$fstype" ] -o [ "$fstype" == "procfs" ]; then continue; fi
		probe -s tscheme -p $device
		if [ -n "$pc" ] -a [ "$tscheme" == "msdos" ]; then
			if test 
				   '(' -f ($device)/bootmgr -a -f ($device)/boot/bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/boot/Bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/boot/BCD ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/Boot/bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/Boot/Bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/Boot/BCD ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/BOOT/bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/BOOT/Bcd ')' 
				   -o 
				   '(' -f ($device)/bootmgr -a -f ($device)/BOOT/BCD ')' 
				; then
				set root="$device"
				ntldr /bootmgr
				boot
			elif test 
				   '(' -f ($device)/ntldr -a -e ($device)/ntdetect.com -a -f ($device)/boot.ini ')' 
				   -o 
				   '(' -f ($device)/ntldr -a -e ($device)/ntdetect.com -a -f ($device)/BOOT.INI ')' 
				   -o 
				   '(' -f ($device)/ntldr -a -e ($device)/NTDETECT.COM -a -f ($device)/boot.ini ')' 
				   -o 
				   '(' -f ($device)/ntldr -a -e ($device)/NTDETECT.COM -a -f ($device)/BOOT.INI ')' 
				   -o 
				   '(' -f ($device)/NTLDR -a -e ($device)/ntdetect.com -a -f ($device)/boot.ini ')' 
				   -o 
				   '(' -f ($device)/NTLDR -a -e ($device)/ntdetect.com -a -f ($device)/BOOT.INI ')' 
				   -o 
				   '(' -f ($device)/NTLDR -a -e ($device)/NTDETECT.COM -a -f ($device)/boot.ini ')' 
				   -o 
				   '(' -f ($device)/NTLDR -a -e ($device)/NTDETECT.COM -a -f ($device)/BOOT.INI ')' 
				; then
				set root="$device"
				regexp -s devnum 'hd([0-9]+)' $root
				if test "$devnum" != "0"; then drivemap -s hd0 $root; fi
				ntldr /ntldr
				boot
			fi
		elif [ -n "$efi" ] -a [ "$fstype" == "fat" ] -a [ "$tscheme" == "gpt" ] -a [ -f ($device)/EFI/Microsoft/Boot/bootmgfw.efi ] -a [ -f ($device)/EFI/Microsoft/Boot/BCD ]; then
			root="$device"
			chainloader /EFI/Microsoft/Boot/bootmgfw.efi
			boot
		fi
		unset tscheme
		unset fstype
	fi
    done
	set root=$saved_root
	if [ "${grub_platform}" == "efi" ]; then set mode="UEFI mode"; else set mode="Legacy BIOS mode"; fi
	echo "Did not find the Windows operating system can be booted in ${mode}."
	echo
	echo -n "Press ESC to return to the menu "
	sleep -i -v 60
}

The above menu will automatically scan and boot into the Windows operating system installed on the computer. Supports Windows Vista, Windows 7 to Windows 10 for both UEFI and Legacy BIOS modes. Supports Windows XP/2003/2000 in Legacy mode. I think Windows 98/ME does not need to be added.

This is my situation:

  • installed Ubuntu without a CD (using unetbootin)
  • dual boot installation (Windows XP+Ubuntu)
  • didn’t like the installation and decided to boot into Windows and delete the Linux partitions
  • forgot to fix the mbr from within Windows

Now, when I boot, I am stuck in the GRUB rescue limbo.

Simple question:
How can I boot into Windows from GRUB rescue?

I cannot boot from CD, therefore the usual solutions (recovery CD etc) do not work.
An older question mentions the possibility to boot Windows but doesn’t specify details: Ubuntu grub rescue prompt

Any hints?

Community's user avatar

asked Oct 11, 2010 at 13:40

pruefsumme's user avatar

When GRUB is gone, so is the ability to boot into Windows. You would now need to boot from the Windows CD to restore the Master Boot Record (MBR). You can also use other boot CDs such as the Ultimate Boot CD for Windows, Bart PE or Hiren’s Boot CD in case you don’t have Windows installation media handy. Here are the steps:

  • Boot from the Windows CD and choose «Repair». Alternatively, boot from one of the other aforementioned boot CDs and run a command prompt.

  • For Windows 8 computers:

    1. Insert disc
    2. set boot order to disc at first priority
    3. reboot, wait for installer to load
    4. select language and keyboard type and click continue
    5. DO NOT CLICK INSTALL, instead click repair my computer in the bottom left corner
    6. click troubleshoot
    7. click advanced
    8. click command prompt and enter the commands below.
    

Add more tutorials for Operating Systems please.

  • Run the the following two commands in a command prompt:

    bootrec /fixmbr
    bootrec /fixboot
    

Scott - Слава Україні's user avatar

answered Apr 29, 2011 at 17:06

Ricky Ricardo's user avatar

3

As Gilles already pointed out, grub rescue only has a few commands which allow you to load modules (e.g. from a grub rescue disk).

In my case — booting from another source wasn’t possible — the only option was to remove the hdd from the computer and use a cheap external hd case to connect the disk to another computer via USB. On that computer, I used MbrFix to fix the mbr.

answered Oct 21, 2010 at 19:41

pruefsumme's user avatar

pruefsummepruefsumme

4211 gold badge4 silver badges7 bronze badges

1

Another tool to add to what Ricky and preufsumme have to say is boot-repair-disk.

answered Aug 9, 2013 at 15:55

PCoder's user avatar

PCoderPCoder

1715 bronze badges

I had this issue just today and solved it by burning boot-repair-disk-64bit.iso to a USB stick (on a Mac using balenaEtcher). Then changed BIOS boot priority to USB stick first and booted it.

In the boot menu selected failsafe mode (normal mode wouldn’t work), and it then suggested to try default recovery. I tried that, it fixed my MBR, and I was then able to boot to Windows 10 again.

answered Mar 24, 2021 at 7:02

Bemmu's user avatar

BemmuBemmu

9781 gold badge9 silver badges15 bronze badges

Boot from the Windows XP/Vista/7 installation CD, and select the Repair (R) option. Select the correct partition, and then enter the Administrator account password. At the command prompt run the following commands:

fixmbr (C:WINDOWSfixmbr.exe)

fixboot (C:WINDOWSfixboot.exe)

Type ‘exit’, and the computer will reboot.

Simon Sheehan's user avatar

answered Jan 20, 2012 at 20:07

Phuqer's user avatar

2

You can use grub rescue to start Windows again.

The command list would be something similar to

rootnoverify (hd0,0)
makeactive
chainloader +1            
boot

NB: this requires the availability of modules that implement all these commands!

From reading over the comments on grub rescue this seems like it’ll work then you can get into windows and reinstall the windows bootloader into the MBR. This only works however if your windows partition is the first partition on the drive AND it’s on the first drive that the computer sees. If you have several drives or SATA drives instead of PATA drives then you may need to use a different command for rootnoverify (try sd0 instead of hd0)

Update me on if it works.

Josip Rodin's user avatar

answered Oct 11, 2010 at 19:53

Kravlin's user avatar

KravlinKravlin

1,1857 silver badges15 bronze badges

4

I had a similar issue, I had to go into the bios to set the boot up sequence to the CD/DVD Drive first so that it would check for the boot stuff there. I am using a solution from somewhere else that told me to first re-install Ubuntu so that the grub loader is installed then you can get back into windows and remove the partition the right way. hope this helps someone out there

answered Dec 11, 2012 at 18:52

Malachi's user avatar

MalachiMalachi

1,0731 gold badge11 silver badges26 bronze badges

Системное администрирование


Рекомендация: подборка платных и бесплатных курсов монтажа видео — https://katalog-kursov.ru/

Наверняка почти у каждого пользователя ОС Linux и ОС Windows, а я имею в виду именно тех, у кого, в силу ряда причин, установлены обе системы, время от времени возникал вопрос: «А нельзя ли, черт возьми, придумать способ, с помощью которого можно было бы устанавливать эти системы в произвольном порядке? Без порчи настроек загрузчика?» Ведь если ставим сначала Windows а потом Linux всё хорошо — линуксовый загрузчик (например GRUB) обычно подхватывает bootmgr. Если ставить в обратном порядке то увы. Даже с использованием GPT + EFI. В случае с EFI нет опасности перезаписи MBR, зато таки есть один нюанс, который лично мне не нравится — установщик Windows в режиме EFI хоть и не перезаписывает сектора диска своим кодом, но зато переопределяет NVRAM, подсовывая туда путь к своему загрузчику. Так что функционал GBUB всё равно приходится восстанавливать. В настройках штатного установщика нет опций для кастомизации процесса установки загрузчика. А что если… не использовать стандартный установщик?! Ну, или почти не использовать…

И такой способ есть. И основан он на технологии установки Windows, которую мы имеем в её дистрибутивах начиная с «семерки». Способ работает для случая Windows версий 7/8/8.1/10, как в случае с MBR + BIOS системы, так в случае с EFI + GPT. Установить систему можно как в раздел HDD, так и на VHD. При этом функционал установщика нужен нам в общем-то для запуска программы настройки BCD-хранилища конфигурации загрузчика. Вместо установочного диска можно использовать загрузочный носитель на основе WinPE. Если бы утилитам bcdedit.exe и BootICE была *nix альтернатива, весь процесс развертывания системы можно было бы вообще выполнить в среде Linux.

Предположим у вас имеется компьютер, с установленным на HDD загрузчиком GRUB2 и свободным разделом, отформатированном в NTFS. Устанавливать будем Windows 7 Ultimate SP1. Для этого потребуются:

  1. Установочный диск с виндой
  2. Чистая флешка объемом >= 4 Gb
  3. Архиватор 7-zip соответствующей разрядности
  4. Утилита BootICE, желательна, но совершенно не обязательна, можно обойтись и bcdedit.exe, входящим в дистрибутив винды

1. Создаем загрузочную флешку

Дело в том, что семерка не хочет устанавливаться в EFI-режиме с DVD. Вот не хочет и всё. К тому же, на установочном носителе нам понадобятся дополнительные утилиты, которые туда надо поместить, а в случае с флешкой это несколько проще, чем в случае с DVD.

Монтируем установочный образ с виндой, допустим он лежит у нас в /home/$USER/install с именем win7-setup.iso

$ mkdir ~/iso
$ sudo mount -t udf ~/install/win7-setup.iso ~/iso

Вставляем флешку в USB-порт. Допустим, она получила имя устройства /dev/sdb. Выполним её разметку в формате MBR

$ sudo fdisk /dev/sdb

Создем на флешке один единственный раздел. После чего форматируем её в FAT
$ sudo mkfs.vfat /dev/sdb1

Копируем содержимое дистрибутива винды на флешку
$ mkdir /tmp/flash
$ sudo mount /dev/sdb1 /tmp/flash -o uid=1000,gid=100,fmask=113,dmask=002
$ cp -rv ~/iso/* /tmp/flash/

Скопируем конфиги EFI-загрузчика на уровень выше

$ cp -rv ~/tmp/flash/efi/microsoft/* ~/tmp/flash/efi/

Теперь нам нужен EFI-загрузчик винды. Его придется выцарапать из дистрибутива. Это легко сделать с помощью архиватора 7-zip, который имеется в репозитории extra/p7zip. Все содержимое дистрибутива винды сжато в образ wim-формата находится на установочном DVD в файле source/install.wim. Обычно этот образ имеет следующую структуру

В каталогах с именами в виде цифр 1-4 находятся разные редакции винды. Чтобы выбрать нужную надо посмотреть внутрь файла с именем [1].xml. Распакуем его в /tmp

$ cd /tmp
$ 7z e ~/iso/sources/install.wim [1].xml

и посмотрим с помощью какого-нибудь браузера, ибо в текстовом редакторе он выглядит ужасно, а специального редактора xml у меня в наличии не оказалось. Каждую редакцию винды описывают структурой вида

где нода EDITIONID указывает на редакцию. Параметр INDEX — как раз номер каталога, в котором валяется нужная редакция. Итак, мне нужна Ultimate, а это индекс 4. Соответсвенно выковыриваем загрузчик оттуда

$ 7z e ~/iso/sources/install.wim 4/Windows/Boot/EFI/bootmgfw.efi

Оки, теперь перенесем полученный файл на флешку

$ mv bootmgfwm.efi /tmp/flash/efi/boot/bootx64.efi

Порядок, теперь у нас в наличии загрузочная флешка для установки винды. Теперь добавим на неё необходимые для установки утилиты — виндозную версию архиватора 7-zip и утилиту BootICE. Архиватор качаем с официального сайта и распаковываем на флешку в каталог utils

$ mkdir -p /tmp/flash/utils/7-Zip/
$ cd /tmp/flash/utils/7-Zip/
$ 7z x ~/downloads/7z1602-x64.exe

Туда же помещаем и bootice

$ cp ~/install/BOOTICEx64.exe /tmp/flash/utils

Уф, всё, отмонтируем флешку
$ cd ~
$ sudo umount /tmp/flash/

Перезагружаемся. Если у вас система с EFI и съемные диски стоят в приоритете загрузки, то компьютер загрузится в установку винды автоматом. Если же появилось таки меню GRUB, ничего страшного, жмем «С» и в консоли набиваем команду exit. Вас вывалит в меню EFI, где выбираем загрузку с флешки. Если же ваша система с BIOS, то тут чуть сложнее, ибо мы не стали заморачиваться с настройкой MBR на флешке. Тогда в консоли GRUB даем команду ls — появится список всех дисков и разделов. Находим нашу флешку, она отобразится в виде (hdX, msdosY), где X, Y — номер диска и раздела соответственно. Теперь вбиваем в консоли команды

grub> set root=hdX,Y
grub> ntldr /bootmgr
grub> boot

Начнется загрузка установщика винды. Он то загрузится, но нам он и не нужен — мы всё будем делать руками. Чтобы стало понятно, что к чему, придется рассмотреть некоторую теорию

2. О развертывании Windows из WIM-образа и капризном нраве Sysprep

Начиная с семерки установка Windows заключается в следующих этапах

  1. Разметка диска в соответствии с архитектурой системы инициализации оборудования. Если BIOS — установщик размечает диск в MBR. При наличии активной EFI — разметка будет GPT.
  2. Распаковка образа install.wim в выбранный для установки раздел
  3. Установка загрузчика и перезагрузка
  4. Инициализация оборудования. Ребут
  5. Локализация, ввод ключа, окончание настройки системы

Это стандартный путь. У нас же диск уже размечен. И нам не нужна автоматическая установка загрузчика — мы поставим его вручную. Разметка диска должна удовлетворять следующим требованиям

  • Если система с EFI на диске должен присутствовать FAT-раздел с типом 0xEF. Если у нас уже установлен линукс с EFI-загрузчиком, то таковой раздел уже имеется
  • Если система с BIOS, то раздел, в котором располагается загрузчик, а это наш NTFS-раздел должен быть активным. Это очень важно! Почему, будет объяснено ниже.

Таким образом, перед распаковкой системы мы должны убедится в том, что перечисленные требования выполнены. После того, как мы распакуем все файл системы и установим загрузчик, система перезагрузиться. После перезагрузки запустится утилита Sysprep, среди прочего настраивающая оборудования и проверяющая конфигурацию системы. Так вот, если в режиме EFI Sysprep не найдет загрузчик и его конфигурацию в EFI-разделе по пути EFI/microsof/boot, а в системе с BIOS каталог Boot и bootmgr будут лежать в неактивном разделе, то Sysprep завершится с ошибкой sysprep generalize error, а в лог, расположенный по адресу WindowsPanthersysperr.log выплюнет что-то похожее на

2015-03-11 16:55:42, Error [0x0e00b3] TOOL Sysprep_Specialize_Bcd: There was an error opening the system store. Status=[0xC0000098]
2015-03-11 16:55:42, Error [0x0f0082] SYSPRP LaunchDll:Failure occurred while executing 'c:WindowsSystem32spbcd.dll,Sysprep_Specialize_Bcd', returned error code 1006
2015-03-11 16:55:42, Error [0x060435] IBS Callback_Specialize: An error occurred while either deciding if we need to specialize or while specializing; dwRet = 0x3ee

и никакие танцы с бубном нам уже не помогут. Винда требует, чтобы загручик лежал в загрузочном разделе и точка. В случае с BIOS просто делаем активным раздел NTFS в котором лежит винда и туда же кладем и загрузчик. Грузится будем всё равно с помощью GRUB, а ему все равно, какой раздел будет активным. В случае с EFI загрузчик придется положить рядом с GRUB в EFI-разделе.

3. Распаковка системы

Итак, определимся, куда мы хотим ставить винду. Можно поставить в NTFS-раздел, а можно и в VHD-диск. Это уж как вам хочется. Я буду показывать процесс на примере с виртуальной машиной EFI, имеющей следующую разметку

The protective MBR's 0xEE partition is oversized! Auto-repairing.

Partition table scan:
MBR: protective
BSD: not present
APM: not present
GPT: present

Found valid GPT with protective MBR; using GPT.

Command (? for help): p
Disk /dev/loop1: 104857600 sectors, 50.0 GiB
Logical sector size: 512 bytes
Disk identifier (GUID): 0D217C93-6699-435A-9BBB-61DFAA6F30B7
Partition table holds up to 128 entries
First usable sector is 34, last usable sector is 104857566
Partitions will be aligned on 2048-sector boundaries
Total free space is 4029 sectors (2.0 MiB)

Number Start (sector) End (sector) Size Code Name
1 2048 206847 100.0 MiB EF00 EFI system partition
2 206848 104855551 49.9 GiB 0700 Basic data partition

На этом диске нет линукса, установлен только GRUB в раздел с EFI. Если мы ставим систему непосредственно в NTFS-раздел, то загружаемся с флешки, дожидаемся запуска программы установки и жмем Shift + F10, чтобы вызвать консоль. Запускаем утилиту diskpart и смотрим список подключенных томов

X:sources> diskpart
DISKPART> list vol

Видим, что флешка (объемом 8 Гб) подключена как диск C:, а раздел для установки вовсе не смонтирован. Непорядок. Делаем так

DISKPART> sel vol 3
DISKPART> remove
DISKPART> assign letter=E
DISKPART> sel vol 1
DISKPART> assign letter=C
DISKPART> list vol
DISKPART> sel vol 2
DISKPART> assign letter=F

Вот теперь порядок, диск на который будем ставить винду стал диском C:, флешка — диском E:, а EFI-раздел — диском F:

Если же мы хотим поставить систему на VHD, то делаем так

DISKPART> sel vol 3
DISKPART> remove
DISKPART> assign letter=E
DISKPART> sel vol 1
DISKPART> assign letter=G
DISKPART> exit

Для порядка создаем каталог с образами
X:sources> md G:vhd
X:sources> diskpart

Создаем виртуальный диск, создаем на нем разметку GPT и раздел NTFS и монтируем его к C:

DISKPART> create vdisk file="G:vhdwin7.vhd" maximum=25600 type=fixed
DISKPART> attach vdisk
DISKPART> clean
DISKPART> convert gpt
DISKPART> create part primary
DISKPART> format fs=ntfs quick
DISKPART> assign letter=C

EFI-раздел монтируем к F:

DISKPART> sel vol 2
DISKPART> assign letter=F

Получаем такую картину

Очень важно! Убеждаемся в том, что EFI-раздел отформатирован именно в FAT, а не в FAT32. Иначе Sysprep не простит нам этой ошибки. Если на компе уже есть линукс, то настройки будут верны.

Теперь распаковываем дистрибутив на диск C:

X:sources> E:
E:> utils7-Zip7zFM.exe

Откроется GUI архиватора 7-zip. В нем открываем каталог E:sources, находим там файл install.wim

Правой кнопкой на этом файле вызываем контектстное меню и переходим по 7-zip -> Открыть архив. Появится содержимое образа.

Лезем в папку 4 — там лежит Ultimate

Выделяем всё Ctrl + A и жмем кнопку «Извлечь». Появится окно, где нам предложат указать путь распаковки

Указываем корень диска C: и жмем ОК.

Ну и теперь, как говорится: «Откиньтесь на спинку кресла и…»

4. Установка и настройка загрузчика

Итак, после некоторого время ожидания распаковка окончена. И вот тут, вот в этом месте винда обчно делает бяку, а именно портит MBR или перенастраивает NVRAM. Но мы не дадим ей этого сделать — мы установим загрузчик вручную.

В случае с EFI, переходим на раздел EFI, смонтированный к F: и создаем необходимые пути и копируем файлы загрузчика

E:> F:
F:> mkdir EFImicrosoftboot
F:> xcopy C:WindowsBootEFI* F:EFImicrosoftboot /s /e
F:> mkdir EFImicrosoftbootFonts
F:> xcopy C:WindowsBootFonts* F:EFImicrosoftbootFonts /s /e
F:> copy C:WindowsSystem32configBCD-Template F:EFImicrosoftbootBCD

Отлично, загрузчик скопирован. Теперь настроим его

F:> E:utilsBOOTICEx64.exe

Открываем файл F:EFIMicrosoftBootBCD. В случае установки на раздел, его параметры задаются так

Если же мы устанавливали систему на VHD, то настройки будут такими

Важно! Имя вторичного загрузчика для EFI-системы winload.efi, для BIOS-системы — winload.exe.

В случае, если мы устанавливаем BIOS-систему установка загрузчика будет выглядеть так

F:> mkdir C:Boot
F:> xcopy C:WindowsBootPCAT* C:Boot /s /e
F:> mkdir C:BootFonts
F:> xcopy C:WindowsBootFonts* C:BootFonts /s /e
F:> copy C:Bootbootmgr C:bootmgr
F:> copy C:WindowsSystem32configBCD-Template C:BootBCD

Важно! Раздел, смонтированный к C: (там где размещен загрузчик) обязан быть активным! Убедитесь в этом перед перезагрузкой!

Настройку выполняем так же точно, используя BootICE.

Ну, вроде все. Закрываем все окна и идем в ребут. Флешку можно вытащить из компа.

5. Скрестим пальцы да вознесем молитвы тебе, о Великий и Ужасный Sysprep…!

GRUB у нас еще не настроен пункта для винды в меню нет. Как только появится меню GRUB жмем «C». В консоли набираем

grub> set root=hdX,Y
grub> chainloader /EFI/Microsoft/Boot/bootmgfw.efi
grub> boot

X, Y — соответственно диск и раздел, где лежит загрузчик. Это в случае EFI. В случае с BIOS делаем так

grub> set root=hdX,Y
grub> ntldr /bootmgr
grub> boot

X, Y — диск и раздел с NTFS. Там где распакована винда и лежит её загрузчик.

В режиме EFI вместо логотипа винды я увидел черный экран, так как не нашел в дистрибутиве билиотеки bootres.dll, которую надо поместить в папку EFIMictosoftBootResourses. В случае с BIOS всё в порядке — знакомая эмблема «семерки». А потом в обоих случаях увидим это

Это работает Sysprep. На 57% моргнет экран — настраивается видяха. И если мы все сделали верно, то надпись «Применение параметров системы» повисит довольно долго, потом система сообщит, что установка будет продолжена после перезагрузки. Если мы где-то напортачили с установкой загрузчика — неправильный EFI раздел или неактивный NTFS, то тогда будет ошибка :( Но мы молодцы и у нас все получится, и после очередной перезагрузки мы увидим это

а потом, наконец вот это

Дальше все как при обычной, штатной установке.

6. Настраиваем GRUB

Обратили внимание на то, что каждый раз мы грузим систему из консоли GRUB руками. Это очень хорошо — значит ни MBR ни NVRAM не перезаписаны коварным майкрософтом. Настало время грузится в арч и добавить в меню GRUB новый пункт

menuentry 'Windows 7 Ultimate SP1 (EFI)' {

set root=hdX,Y
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
}

в случае EFI. Или

menuentry 'Windows 7 Ultimate SP1' {

set root=hdX,Y
ntldr /bootmgr
}

в случае BIOS. Применяем настройки GRUB и перезагружаемся и видем систему в пункте меню загрузки

после выбора которого получаем загруженную Windows

Заключение

Упреждая гнев профессиональных win-админов, скажу сразу — я знаю о DISM. Именно информация об этой системе и привела меня к описанному решению. Цель была одна — выяснить сколько нужно возможностей собственно Windows для установки Windows.

Оказалось вот что — для установки Windows её среда необходима только для одного — настройки BCD-хранилища. Всё. Остальное можно сделать из среды любой другой операционной системы.

Если написать аналог bcdedit.exe под Linux, то установить Windows можно будет с линуксового Live-носителя.

Понравилась статья? Поделить с друзьями:
  • How to add windows 10 to grub
  • How to add user in windows 10
  • How to add ubuntu to windows 10 boot manager
  • How to add system windows forms
  • How to add russian language to windows 10