Перезагрузка по расписанию windows server 2003

It is not uncommon for s server to require a reboot after a Windows Update, Malware Protection install, backup software install, or pretty much any third party software that runs as a service.  However, most businesses prefer any Network downtime to occur after hours.

Blog.jpg

Blog

The Internet Innovations Group website blog is a collection of management or technical insight gained from daily consulting or support calls with our clients.

It is not uncommon for a server to require a reboot after a Windows Update, virus protection install, backup software install, or pretty much any third party software that runs as a service.  However, most businesses prefer any Network downtime to occur after hours.

 

Most businesses prefer any Network downtime to occur after hours.

Accordingly, the solution is to schedule an unattended server reboot.  Following are the steps to perform an unattended and scheduled reboot of a Windows 2003 Server.

Before you proceed, some things to consider: 

  • Make sure you have previously performed a manual reboot and know for a fact that the server will reboot successfully without requiring user interaction to complete it’s reboot. Make sure your server doesn’t have BIOS prompts that require you to press F1 or similar to continue.  Make sure, you don’t have any failed Services at start-up that require a manual start.
  • Make sure there are no Scheduled Tasks or other schedule processes that run at the time when you plan to schedule the reboot.

Summary

  1. Create batch file containing the commands to reboot the server
  2. Create a Scheduled Task to execute the batch file

Step by step:

Create Batch File

  1. Open Notepad
  2. Type a line with the following: shutdown -r -f -t 30
  3. Select Save As from the File menu and change the extension from .TXT to .BAT. Place file on local server hard drive (remember location).  The location must be accessible via the User Account whose permission you will use of the Scheduled Task.

Create Scheduled Task

  1. Schedule Batch file as Scheduled Task via Control Panel.
  2.  Browse for previously created Batch file.
  3. Select appropriate Administrator account to execute Scheduled task.
  4. IMPORTANT: Schedule task to run «once», unless you want to be rebooting server on a regular basis daily, weekly, monthly, etc. 

Sample Scheduled Task Entry

Sample Scheduled Task Schedule Tab

Sample Scheduled Task Permissions

We hope our insight has been helpful.  This is just one of many common IT issues we handle on a daily basis as part of our Network, Server, and Desktop support; or it may be insight resulting from our Website, Mobile App, or Database development projects.

If you would like to take advantage of our insight for your daily IT Support and IT Projects, please feel free to contact us.

Click for Contact Information

Internet Innovations Group

Internet and Network Integration Services

Pennsylvania based business providing Internet and Network Integration Services to Small and Midsize businesses.  Services include Website Design, Mobile Device Enabled Websites, Microsoft Servers Support, Router and Wireless Configurations.  Specializing in Squarespace Hosted Websites.

P. 570.267.4671

F. ​866.877.4284

​e. info@internetinnovationsgroup.com

i. www.internetinnovationsgroup.com

Internet Innovations Group | , Clarks Summit, PA 18411, USA

В Windows XP: Пуск — Панель управления — ярлык «Назначенные задания» либо Пуск — Все программы — Стандартные — Служебные — Назначенные задания

В Windows 7: Пуск — Панель управления — Администрирование — Расписание выполнения задач либо Пуск — Все программы — Стандартные — Служебные — Планировщик заданий

В Windows 8: Пуск — Панель управления — Администрирование — Расписание выполнения задач

Далее:

  1. Заходим в планировщик задач (Пуск+R, вводим в строку C:\Windowssystem32taskschd.msc /s).
  2. Создаём Простую задачу:
  3. Вводим Имя задачи, жмём Далее.
  4. Оставляем галочку на Ежедневно и жмём Далее.
  5. Далее вписываем нужное Время для перезагрузки и жмём Далее.
  6. Оставляем галочку на «Запустить программу», снова жмём Далее.
  7. В поле «Программа или сценарий» вводим C:WindowsSystem32shutdown.exe,
  8. В поле «Добавить аргументы» вводим -r и снова давим Далее, и Готово.
  9. Для повторения задачи каждые N часов надо проделать эти действия сколько нужна устанавливая разное время.
  10. Также для автоматического выключения ПК надо проделать тот же путь, только в поле Добавить аргументы вводим -s.

Примеры использования Shutdown в Windows 10:

shutdown.exe /r /t0 — Немедленная перезагрузка компьютера
shutdown.exe /r — перезагрузка ПК через 30 секунд
shutdown.exe /r /t 3600 — перезагрузка Windows через 60 минут
shutdown.exe /s /t 0 — Немедленное Выключение
shutdown.exe /s — Выключение ПК через 30 секунд
shutdown.exe /s /t 3600 — Выключение компьютера через час
shutdown.exe /h — Переводим систему в режим Гибернации (Hybernate) при условии, что этот режим включен
shutdown.exe /l — Завершение сеанса пользователя
shutdown.exe /i — Запуск графического интерфейса выключения ПК

Параметры командной строки:

/i — Отображение графического интерфейса пользователя. Этот параметр должен быть первым.
/l — Завершение сеанса. Этот параметр нельзя использовать с параметрами /m или /d.
/s — Завершение работы компьютера.
/r — Завершение работы и перезагрузка компьютера.
/g — Завершение работы и перезагрузка компьютера. После перезапуска системы, запуск всех зарегистрированных приложений.
/a — Отмена завершения работы системы. Этот параметр можно использовать только в период ожидания.
/p — Немедленное отключение локального компьютера без предупреждения. Можно использовать с параметрами /d и /f.
/h — Переключение локального компьютера в режим гибернации. Можно использовать с параметром /f.
/e — Указание причины непредвиденного завершения работы компьютера.
/o — Переход в меню дополнительных параметров загрузки и перезагрузка компьютера. Данный параметр допустим для Windows 8 и более поздних версий. Необходимо использовать в с параметром /r.
/m \компьютер — Имя или IP-адрес конечного компьютера.
/t xxx — Задание задержки в xxx секунд перед завершением работы компьютера. Допустимый диапазон: 0-315360000 (10 лет); значение по умолчанию: 30 секунд. Если период таймаута больше 0, применяется параметр /f.
/c «комментарий» — Комментарий с причиной перезапуска или завершения работы. Наибольшая длина — 512 знаков.
/f — Принудительное закрытие запущенных приложений без предупреждения пользователей. Параметр /f используется, если для параметра /t задано значение больше 0.
/d [p|u:]xx:yy Необходимо указать причину для перезагрузки или выключения. «p» означает запланированную перезагрузку или завершение работы. «u» означает, что причина определяется пользователем. Если не задано ни «p», ни «u», перезагрузка или завершение работы являются незапланированными. xx является основным кодом причины (целое положительное число, меньшее 256). yy является вспомогательным кодом причины (целое положительное число, меньшее 65536).

Вместо синтаксиса /ключ допускается использование -ключ

Перезагрузку Windows сервера или настольного персонального компьютера по расписанию можно реализовать средствами встроенного компонента Microsoft Winodows — планировщика заданий, возможности которого позволяют производить запуск скриптов или программ в заданные моменты времени. Функционально и внешне компонент не имеет никаких отличий в разных версия операционной системы и алгоритм взаимодействия универсален.

Запускаем планировщик заданий любым удобным способом. Например, находим в панели управления или при нажатии сочетания клавиш Пуск+R, вводим в строку taskschd.msc или щелкаем правой кнопкой на меню Пуск и выбираем «Управление компьютером».

Окно управления компьютером с открытым планировщиком заданий.
Окно управления компьютером с открытым планировщиком заданий.

Создаем простую задачу. Обязательными полями для заполнения являемся Имя, а поле Описание опционально, заполните его при необходимости.

Окна мастера создания простой задачи.
Окна мастера создания простой задачи.

Определяемся с желаемым графиком запуска нашей задачи автоматической перезагрузки компьютера. Мастер довольно гибко позволяем настроить время и интервалы выполнения (ежедневно, еженедельно, ежемесячно).

Мастер создания простой задачи.
Еженедельно в воскресенье и четверг в 4.00 утра отлично подойдут для перезагрузки.
Еженедельно в воскресенье и четверг в 4.00 утра отлично подойдут для перезагрузки.

Дальше выбираем «Запустить программу» в качестве действия для задачи. Финальным аккордом указываем приложение shutdown.exe используемое в операционной системе как утилита для выключения, перезагрузки или завершения сеанса пользователя.

C:WindowsSystem32shutdown.exe

Обязательно добавляем аргументы для достижения правильного результата. Ключевыми значениями для нас являются /r — перезагрузка, /f — принудительное закрытие всех приложений. Подробнее можно ознакомиться и подобрать аргументы в справочном материале.

Завершаем настройку и ждем время указанное в графике для проверки результата.

shutdown /r /f
shutdown /r /f

Автор: Федотов Илья

 

Hello Madal,

Thank you for your reply.

“Is there a way to encrypt the password ?”

 Based on my research, you can create a “Schtasks Helper script” and “Encode” it to improve security as described in the following example:

1. On this share create a VBS file called Schtasks.vbs with the following code:

Schtasks.vbs

set shell=wscript.createobject(«Wscript.shell»)

shell.run «schtasks /create /ru <administrator> /rp <password> /sc dialy /st 23:59:00 /tn shutdown /tr \servershareshutdown.bat

shutdown.bat

shutdown /t 0 /r

2. Download the Windows Script Encoder from:

http://www.microsoft.com/downloads/details.aspx?FamilyID=e7877f67-c447-4873-b1b0-21f0626a6329&displaylang=en&Hash=2eeLrR1Fo%2bgy0pOMTILIDCo2B6FWF5ncnlQW61ur2UdX0K7ZsIKKjttmjR%2bpFX5MMlQ4EW7GWRIwNA%2f4WFS0rw%3d%3d

3. Encrypt the original .vbs file:

screnc original_vbs_file.vbs vbs_encrypted_file.vbe

The script encoder is a command-line tool that allows a scriptwriter to protect the contents of a script from unauthorized copies or modifications while (at the same time) allowing the script to run.

Disclaimer

This sample script is not supported under any Microsoft standard support program or service. The sample script is provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for

any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages

Actually, I also agree with Darren. You may use Group Policy Preferences to achieve the goal. It is a feature new in Microsoft Windows Server 2008. Group Policy preferences include mapped drives, scheduled tasks, and Start menu settings. For many types of operating system and application settings, using Group Policy preferences is a better alternative to configuring them in Windows images or using logon scripts. In fact, the new policy features in GPP support XP, Server 2003, Vista and Server 2008 “clients”. In order for clients to process GPP policy settings, they must install the GPP Client Side Extension (CSE) package, which is available from following site.

Group Policy Preference Client Side Extensions for Windows XP

http://www.microsoft.com/downloads/details.aspx?familyid=E60B5C8F-D7DC-4B27-A261-247CE3F6C4F8&displaylang=en

For more details, you can download Group Policy Preferences Overview

http://www.microsoft.com/downloads/details.aspx?FamilyID=42e30e3f-6f01-4610-9d6e-f6e0fb7a0790&DisplayLang=en

regards,


Nick Gu — MSFT

  • Proposed as answer by
    madal
    Friday, January 9, 2009 5:31 PM
  • Marked as answer by
    Nick Gu — MSFT
    Monday, January 12, 2009 4:18 AM

 

Hello Madal,

Thank you for your reply.

“Is there a way to encrypt the password ?”

 Based on my research, you can create a “Schtasks Helper script” and “Encode” it to improve security as described in the following example:

1. On this share create a VBS file called Schtasks.vbs with the following code:

Schtasks.vbs

set shell=wscript.createobject(«Wscript.shell»)

shell.run «schtasks /create /ru <administrator> /rp <password> /sc dialy /st 23:59:00 /tn shutdown /tr \servershareshutdown.bat

shutdown.bat

shutdown /t 0 /r

2. Download the Windows Script Encoder from:

http://www.microsoft.com/downloads/details.aspx?FamilyID=e7877f67-c447-4873-b1b0-21f0626a6329&displaylang=en&Hash=2eeLrR1Fo%2bgy0pOMTILIDCo2B6FWF5ncnlQW61ur2UdX0K7ZsIKKjttmjR%2bpFX5MMlQ4EW7GWRIwNA%2f4WFS0rw%3d%3d

3. Encrypt the original .vbs file:

screnc original_vbs_file.vbs vbs_encrypted_file.vbe

The script encoder is a command-line tool that allows a scriptwriter to protect the contents of a script from unauthorized copies or modifications while (at the same time) allowing the script to run.

Disclaimer

This sample script is not supported under any Microsoft standard support program or service. The sample script is provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for

any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages

Actually, I also agree with Darren. You may use Group Policy Preferences to achieve the goal. It is a feature new in Microsoft Windows Server 2008. Group Policy preferences include mapped drives, scheduled tasks, and Start menu settings. For many types of operating system and application settings, using Group Policy preferences is a better alternative to configuring them in Windows images or using logon scripts. In fact, the new policy features in GPP support XP, Server 2003, Vista and Server 2008 “clients”. In order for clients to process GPP policy settings, they must install the GPP Client Side Extension (CSE) package, which is available from following site.

Group Policy Preference Client Side Extensions for Windows XP

http://www.microsoft.com/downloads/details.aspx?familyid=E60B5C8F-D7DC-4B27-A261-247CE3F6C4F8&displaylang=en

For more details, you can download Group Policy Preferences Overview

http://www.microsoft.com/downloads/details.aspx?FamilyID=42e30e3f-6f01-4610-9d6e-f6e0fb7a0790&DisplayLang=en

regards,


Nick Gu — MSFT

  • Proposed as answer by
    madal
    Friday, January 9, 2009 5:31 PM
  • Marked as answer by
    Nick Gu — MSFT
    Monday, January 12, 2009 4:18 AM

Profile picture for user Олег

Windows Server

Имеем Windows Server 2012 R2. Задача — автоматически перезагружать сервер каждый понедельник в 5 утра. Приступаем.

Запускаем Планировщик заданий, создаём в нём папку «reboot»:

reboot

Делаем Create Basic Task… Запускается мастер:

reboot

Указываем Name, Description:

reboot

Кликаем Next:

reboot

Выбираем период Weekly. Next:

reboot

Указываем начало — ближайший понедельник 5 утра. Ставим галку Monday. Next:

reboot

Выбираем Start a program. Next:

reboot

В Program/script: пишем:

%SYSTEMROOT%System32shutdown.exe

В Add arguments (optional):

/r /f /t 90 /d p:0:0 /c "Перезапуск по понедельникам. Отмена: shutdown.exe /a"

Где:

  • /r — перезагрузка,
  • /f — принудительное закрытие всех приложений,
  • /t 90 — время ожидания до начала перезагрузки 90 сек,
  • /d p:0:0 — причины перезагрузки для журнала. В данном случае, мы указали: p — запланированная перезагрузка, 0:0 — «Other (planned)»,
  • /c  комментарий в свободной форме длинной не более 512 символов. Комментарий будет показываться юзерам 90 секунд. За это время можно отменить перезагрузку командой shutdown.exe /a.

Список параметров и причин перезагрузки можно посмотреть shutdown.exe /?

reboot

Мастер не доделали, кликаем Finish. Создаётся задача  — редактируем её.

win

Ставим Run whether user is logged on or not. Добавим галку Run with highest privileges. Ok:

reboot

Нас попросят ввести имя пользователя, от имени которого будет выполняться задание. И пароль. Готово:

win

Сам пока не проверял результатов. В ближайший понедельник посмотрим…

P.S.

Две недели прошло — шедулер нормально перезагружает сервер по понедельникам.

Понравилась статья? Поделить с друзьями:
  • Перезагрузка ноутбука с клавиатуры windows 10
  • Перезагрузка ноутбука в безопасном режиме windows 10
  • Перезагрузка компьютера через планировщик заданий windows 10
  • Перезагрузка компьютера самопроизвольно на windows 10 в игре
  • Перезагрузка компьютера по таймеру windows 10