- What are the system recovery options in Windows?
- What each recovery option does
- To open the System Recovery Options menu on your computer
- To open the System Recovery Options menu using the Windows 7 installation disc or a USB flash drive, or a system repair disc
- Управление средой восстановления Windows (Windows RE)
- Отключение и включение WinRE
- Проверка записей WinRE в файле конфигурации BCD
- Метаположение файла Winre.wim
- Сброс настроек в файле ReAgent.xml
- Ручной поиск и восстановление файла Winre.wim
- How can a windows service programmatically restart itself?
- 17 Answers 17
- How windows recovery work with failure count?
What are the system recovery options in Windows?
Support for Windows 7 ended on January 14, 2020
We recommend you move to a Windows 10 PC to continue to receive security updates from Microsoft.
The System Recovery Options menu contains several tools, such as Startup Repair, that can help you recover Windows from a serious error. This set of tools is on your computer’s hard disk and on the Windows installation disc.
Note: You can also create a system repair disc that contains the System Recovery Options menu. For more information, see Create a system repair disc. If you use a Tablet PC or other computer with a touchscreen, you might need to connect a keyboard and mouse in order to use Startup Repair and the other tools in the System Recovery Options menu.
What each recovery option does
System recovery option
Fixes certain problems, such as missing or damaged system files, that might prevent Windows from starting correctly.
Restores your computer’s system files to an earlier point in time without affecting your files, such as e‑mail, documents, or photos.
If you use System Restore from the System Recovery Options menu, you cannot undo the restore operation. However, you can run System Restore again and choose a different restore point, if one exists.
System Image Recovery
You need to have created a system image beforehand to use this option. A system image is a personalized backup of the partition that contains Windows, and includes programs and user data, like documents, pictures, and music.
Windows Memory Diagnostic Tool
Scans your computer’s memory for errors.
Advanced users can use Command Prompt to perform recovery-related operations and also run other command line tools for diagnosing and troubleshooting problems.
Note: Some computer manufacturers might customize the menu by adding or removing recovery tools, or including their own tools.
To open the System Recovery Options menu on your computer
Remove all floppy disks, CDs, and DVDs from your computer, and then restart your computer using the computer’s power button.
Do one of the following:
If your computer has a single operating system installed, press and hold the F8 key as your computer restarts. You need to press F8 before the Windows logo appears. If the Windows logo appears, you need to try again by waiting until the Windows logon prompt appears, and then shutting down and restarting your computer.
If your computer has more than one operating system, use the arrow keys to highlight the operating system you want to repair, and then press and hold F8.
On the Advanced Boot Options screen, use the arrow keys to highlight Repair your computer, and then press Enter. (If Repair your computer isn’t listed as an option, then your computer doesn’t include preinstalled recovery options, or your network administrator has turned them off.)
Select a keyboard layout, and then click Next.
On the System Recovery Options menu, click a tool to open it.
To open the System Recovery Options menu using the Windows 7 installation disc or a USB flash drive, or a system repair disc
If your computer’s system is severely damaged and you can’t access the System Recovery Options menu on your computer, you can access it using the Windows 7 installation disc or a USB flash drive, or using a system repair disc if you created one earlier.
To use this method, you need to restart (boot) your computer using the disc or USB flash drive.
Insert the Windows 7 installation disc or USB flash drive, or a system repair disc, and then shut down your computer.
Restart your computer using the computer’s power button.
When prompted, press any key, and then follow the instructions that appear.
On the Install Windows page, or on the System Recovery Options page, choose your language and other preferences, and then click Next.
If neither the Install Windows page nor the System Recovery Options page appear, and you’re not asked to press any key, you might need to change some system settings.
If you’re using the Windows installation disc or USB flash drive, click Repair your computer.
Select the Windows installation you want to repair, and then click Next.
On the System Recovery Options menu, click a tool to open it.
Управление средой восстановления Windows (Windows RE)
Среда восстановления Windows Recovery Environment (WinRE) представляет собой минимальную ОС на базе среды предварительной установки Windows Preinstallation Environment (WinPE) , в которую включен ряд инструментов для восстановления, сброса и диагностики ОС Windows. В том случае, если основная ОС по какой-то причине перестает загружаться, компьютер пытается запустить среду восстановления WinRE, которая в автоматическом (или ручном режиме) может помочь исправить возникшие проблемы.
В некоторых случаях компьютер не может загрузиться в среде Windows Recovery Environment из-за различных проблем. В этой статье мы рассмотрим основные способы восстановления среды WinRE на примере Windows 10 (для Windows 7 и Windows 8.1 процедура аналогична).
Причины, по которым среда WinRE перестает грузится или работает некорректно, в общем случае могут быть разными:
- Среда WinRE отключена на уровне настроек Windows.
- В хранилище конфигурации загрузки ( BCD ) отсутствуют записи для загрузки в режиме восстановления
- Файл с образом среды winre.wim отсутствует или перемещен
- Отсутствует или содержит некорректные данные файл конфигурации WinRE — ReAgent.xml
Отключение и включение WinRE
Попробуйте отключить и включить режим WinRE, выполнив в командной строке с правами администратора следующие команды:
Проверка записей WinRE в файле конфигурации BCD
Проверьте, что в конфигурации загрузки BCD (Boot Configuratin Data) имеются корректные записи для загрузки WinRE.
Примечание. При успешном включении WinRE с помощью reagent, в конфигурации загрузки должны автоматически появится нужные записи для WinRE. Однако в любом случае стоит проверить значение параметра recoverysequence .
Выведем текущие записи в BCD
bcdedit /enum all
В списке вариантов загрузки найдите секцию Windows Boot Loader , с идентификатором identifier= . В нашем примере эта запись выглядит таким образом:
Windows Boot Loader
——————-
identifier
device partition=C:
path \Windows\system32\winload.exe
description Windows 10
locale ru-RU
inherit
recoverysequence <7c817935-e52f-11e6-9c2c-0050569efccb>
recoveryenabled Yes
allowedinmemorysettings 0x15000075
osdevice partition=C:
systemroot \Windows
resumeobject <1c7df7a0-4560-11e5-9675-8451eaa913bb>
nx OptIn
bootmenupolicy Standard
Найдите и запомните значение GUID в атрибуте recoverysequence (в нашем примере это
Далее нужно найти секцию конфигурации загрузки, у которой значение идентификатора ( identifier ) равно полученному выше GUID, а в описании поля ( description ) указано Windows Recovery Environment . Эта запись может выглядеть так:
Windows Boot Loader
——————-
identifier <7c817935-e52f-11e6-9c2c-0050569efccb>
device ramdisk=[F:]\Recovery\WindowsRE\Winre.wim,<7c817936-e52f-11e6-9c2c-0050569efccb>
path \windows\system32\winload.exe
description Windows Recovery Environment
locale ru-RU
inherit
displaymessage Recovery
osdevice ramdisk=[F:]\Recovery\WindowsRE\Winre.wim,<7c817936-e52f-11e6-9c2c-0050569efccb>
systemroot \windows
nx OptIn
bootmenupolicy Standard
winpe Yes
В том случае, если такая запись не была найдена, ищите другую запись BCD с другим GUID в качестве идентификатора, с текстомWindows Recovery Environment в поле description , которая в значениях device и osdevice содержит путь к файлу Winre.wim.
Путь к wim файлу может указывать на другой диск (к примеру, [\Device\HarddiskVolume2]). Если такая секция найдена, можно привязать данную запись для загрузки WinRe в качестве среды восстановления для текущей системы. Скопируйте GUID найденной записи и замените его в следующей команде:
bcdedit /set
Примечание . Если вы используете мультизагрузку, имейте в виду, что каждая ОС будет добавлять в Microsoft Boot Manager собственную запись для среды Windows Recovery Environment. Здесь важно не запутаться в них.
Метаположение файла Winre.wim
Убедитесь, что файл Winre.wim находится по указанному пути. Как правило, он хранится в одном из следующих местоположений (папки скрытые ): каталоге C:\Windows\System32\Recovery, на отдельном скрытом разделе System Reserved , либо на разделе восстановления от производителя. В нашем примере он должен находится на диске F:\ в каталоге \Recovery\WindowsRE\Winre.wim.
Также проверьте путь к wim файлу, который указан в файле ReAgent.xml (находится в каталоге C:\Windows\System32\Recovery либо в каталоге Recovery на разделе восстановления). Откройте данный файл с помощью любого редактора и проверьте значение атрибута . В том случае, если указанный там путь не существует (оригинальный раздел был удален), можно изменить путь на
Совет. Текущую конфигурацию Recovery Agent можно получить командой reagentc /info. Эта команда поможет определить идентификатор записи в BCD (Boot Configuration Data (BCD) identifier) и путь к образу Windows RE (location: \\?\GLOBALROOT\device\harddisk0\partition1\Recovery\WindowsRE)
Сброс настроек в файле ReAgent.xml
В том случае, если методики выше не помогли восстановить работоспособность WinRe, можно попробовать сбросить настройки в файле ReAgent.xml (предварительно сделайте его копию).
В Windows 8 /10 будет достаточно удалить файл ReAgent.xml и он будет автоматически создан при следующем ключении WinRE командой reagentc /enable .
В Windows 7/ Vista откройте файл ReAgent.xml с помощью редактора (лучше всего Notepad++) и очистите значения следующих параметров WinreBCD , WinreLocation , ImageLocation , InstallState , WinREStaged :
Сохраните изменения, проверьте, что файл Winre.wim присутствует в папке %windir%\System32\Recovery. Включите WinRE командой
Ручной поиск и восстановление файла Winre.wim
В том случае, если ни в одном из стандартных каталогов нет файла Winre.wim, попробуйте найти его поиском с помощью файлового менеджера или такой командой:
dir /a /s c:\winre.wim
Совет . Не забудьте поискать данный файл и на скрытых разделах, которым нужно предварительно назначить букву диска.
Если вы нашли файл, скопируйте в стандартное местоположение его следующими командами:
attrib -h -s c:\Recovery\3b09be7c-2b1f-11e0-b06a-be7a471d71d6 \winre.wim
xcopy /h c:\Recovery\3b09be7c-2b1f-11e0-b06a-be7a471d71d6 \winre.wim c:\Windows\System32\Recovery
Если найти файл не удалось, скопируйте его с аналогичной системы (версия и битность ОС должна совпадать), либо с дистрибутива. Для этого, нужно на DVD/ ISO образе с помощью 7-Zip открыть файл \sources\install.wim и извлечь файл \Windows\System32\Recovery\Winre.wim в каталог c:\Windows\System32\Recovery.
Заменим путь к файлу в конфигурации Recovery Agent:
reagentc /setreimage /path C:\windows\system32\recovery
Осталось включить Windows Recovery Agent командой:
How can a windows service programmatically restart itself?
I need to write robust code in .NET to enable a windows service (server 2003) to restart itself. What is the best way to so this? Is there some .NET API to do it?
17 Answers 17
Set the service to restart after failure (double click the service in the control panel and have a look around on those tabs — I forget the name of it). Then, anytime you want the service to restart, just call Environment.Exit(1) (or any non-zero return) and the OS will restart it for you.
You can’t be sure that the user account that your service is running under even has permissions to stop and restart the service.
where SERVICENAME is the name of your service (double quotes included to account for spaces in the service name, can be omitted otherwise).
Clean, no auto-restart configuration necessary.
You can create a subprocess using Windows cmd.exe that restarts yourself:
It would depend on why you want it to restart itself.
If you are just looking for a way to have the service clean itself out periodically then you could have a timer running in the service that periodically causes a purge routine.
If you are looking for a way to restart on failure — the service host itself can provide that ability when it is setup.
So why do you need to restart the server? What are you trying to achieve?
I don’t think you can in a self-contained service (when you call Restart, it will stop the service, which will interrupt the Restart command, and it won’t ever get started again). If you can add a second .exe (a Console app that uses the ServiceManager class), then you can kick off the standalone .exe and have it restart the service and then exit.
On second thought, you could probably have the service register a Scheduled Task (using the command-line ‘at’ command, for example) to start the service and then have it stop itself; that would probably work.
The problem with shelling out to a batch file or EXE is that a service may or may not have the permissions required to run the external app.
The cleanest way to do this that I have found is to use the OnStop() method, which is the entry point for the Service Control Manager. Then all your cleanup code will run, and you won’t have any hanging sockets or other processes, assuming your stop code is doing its job.
To do this you need to set a flag before you terminate that tells the OnStop method to exit with an error code; then the SCM knows that the service needs to be restarted. Without this flag you won’t be able to stop the service manually from the SCM. This also assumes you have set up the service to restart on an error.
Here’s my stop code:
If the service runs into a problem and needs to restart, I launch a thread that stops the service from the SCM. This allows the service to clean up after itself:
How windows recovery work with failure count?
I am using the following command to configure the service failure recovery
(used notepad2.exe just for testing)
From the Microsoft documentation here:-
This field contains an array of integer values that specify the actions taken by the SCM if the service fails. Separate the values in the array by [
]. The integer value in the Nth element of the array specifies the action performed when the service fails for the Nth time.
So, what I am getting from this is the count of failure will decide the action => For first failure Actions[0] will be executed and for the second Actions[1] will be executed and for all subsequent failures Actions[2] will be
I have following configuration for the service for testing this behavior:-
Then I tried killing the process under which service is running by using taskkill .
Here is the first log
Then I tried starting the service manually.
Then again I tried killing the service after
2 mins ( => the reset count will set failure count to 0 as it is configured to 1 minute).
Here is the log for the error
In above figure, it is clear that why count is resetting to 0 because reset setting we have given 60 sec and our service was running more than 2 mins .
But the action described for recovery is wrong as Restarting the service is the action for the second failure not for the first failure.
So why the count for failure is coming 1 but the action for recovery is the action corresponding to the second failure action?