-
Категория:
Технические советы -
– Автор:
Игорь (Администратор)
- Редактор локальной групповой политики Windows
- Запуск сценария или программы при завершении работы Windows
- Запуск сценария или программы при выходе пользователя из системы Windows
Вы когда-нибудь хотели запустить программу или сценарий при выключении компьютера или при выходе пользователя из системы? В конце дня вызвать программу для очистки временных файлов или запустить резервное копирование регулярно используемых файлов. Несмотря на то, что выполнить автоматический запуск программы при старте Windows достаточно просто, настройка запуска программ при выключении не столь очевидна. Немногие пользователи об этом знают, но во многих версиях Windows есть встроенный инструмент, который позволяет сделать это достаточно просто.
Редактор локальной групповой политики Windows
Хитрость заключается в том, чтобы использовать системный инструмент Windows под названием «Редактор локальной групповой политики» (GPE). К сожалению, Microsoft исключила GPE из всех Home версий, так что этот метод применим только к таким версиям, как Professional и Enterprise. Метод подходит для Windows XP и выше. Возможно вы уже знакомы с GPE, так как данный инструмент представляет множество удобных функций. Тем не менее, даже в таком случае, о возможности запуска сценариев и программ знают немногие.
Примечание: Как альтернативу, вы всегда можете использовать vbs-сценарии или пакетные файлы, вызов которых будет заканчивается запуском консольной команды выключения компьютера.
GPE является одним из системных модулей Windows, известных под названием консоль управления Microsoft или оснастка. Хоть, некоторые из них можно запустить из панели управления Windows, найти их в списках программ нельзя. Учтите, что для запуска оснасток потребуются права администратора.
Запуск сценария или программы при завершении работы Windows
- Чтобы вызвать GPE, откройте окно «Выполнить», при помощи комбинации клавиш «WinKey (Клавиша Windows) + R». Или выполните следующий пункт в строке поиска меню Пуск.
- В поле ввода введите «gpedit.msc» (без кавычек) и нажмите Enter
- В левой панели диалогового окна GPE последовательно раскройте вкладки «Конфигурация компьютера» и «Конфигурация Windows», а затем выберите пункт «Сценарии (запуск/завершение)», как это показано на рисунке выше
- В правой панели окна дважды щелкните на пункте «Завершение работы»
- В открывшемся диалоговом окне нажмите кнопку «Добавить»
- Откроется окно, показанное ниже.
- В поле «Имя сценария» укажите путь до исполняемого файла, который хотите запустить при выключении Windows. Или выберите файл из формы выбора, которая появится по нажатию на кнопку «Обзор…»
- В поле «Параметры сценария» укажите необходимые параметры, если это необходимо
- Нажмите «OK».
Запуск сценария или программы при выходе пользователя из системы Windows
Если вам необходимо запускать программу или сценарий только при выходе пользователя из системы, то в оснастке GPE необходимо использовать другой пункт. Сама инструкция остается точно такой же. Единственно, вам необходимо на шаге 3 раскрыть вместо вкладки «Конфигурация компьютера» вкладку «Конфигурация пользователя». И на шаге 4 дважды щелкнуть на пункте «Выход из системы» вместо «Завершение работы»
Примечание: Данная статья в большей степени предназначена для опытных пользователей. Дополнительные сведения об использовании и планировании через GPE можно найти на сайте Microsoft по этой ссылке.
Теперь вы знаете как запустить исполняемый файл при выключении Windows и при выходе пользователя из системы.
☕ Понравился обзор? Поделитесь с друзьями!
-
Как узнать какие программы подключены к Интернету (CurrPorts)?
Технические советы -
Как узнать какие процессы Windows используют файл?
Технические советы -
Как отключить историю поисковых запросов для аккаунтов Google?
Технические советы -
Программа Hwinfo характеристики компьютера и проверка состояния устройств в Windows
Технические советы -
Как закрепить на панели задач в Windows 7 что угодно?
Технические советы -
Как отменить подписку или удалить аккаунты из онлайн-сервисов?
Технические советы
Добавить комментарий / отзыв
Well, its an easy way of doing some registry changes:
I tried this on 2008 r2 and 2016 servers.
Things need to be done:
- Create a text file «regedit.txt«
- Paste the following code in it:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"IsPowershell"=dword:00000000
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
-
Save this file as regedit.reg extension
-
Run it on any command line using below command:
regedit.exe /s regedit.reg
I need to run batch scripts at shutdown of Windows 10 home edition, both on manual restarts and on automatic restarts due to Windows automatic updates. This needs to work while no users are logged in too.
So far I’ve tried:
- Scheduled Task at eventid 1047 (discarded, won’t wait till my script is over).
- Manually adding Group Policy shutdown scripts to registry and to C:\WINDOWS\SYSTEM32\GroupPolicy (discarded, won’t run since it looks like the functionality is disabled by restraints imposed by the Windows edition.)
- Third party software. Weird enough, I couldn’t find any free tool that would run as a service and allow me to add .bat files to be run at system (or service) shutdown.
- I tried AutoHotkey + NSSM [The Non-Sucking Service Manager] as a custom service, but AutoHotkey’s events wouldn’t trigger every time.
I’m quite disenchanted with this limitation. 🙁
Any ideas?
Edit1: Take into account Windows automatic updates.
Edit2: This needs to work while no users are logged in too.
Edit4: I’m waiting for the next Windows automatic restart due to a Windows update to see if running shutdown -a
at the beginning of the batch file and then shutdown -s
at the end within a scheduled task at shutdown event approach works.
Edit5: Bummer, it didn’t work. The scheduled task did not start: Error: «Shutdown in progress». I guess my only hope is a third-party tool.
Hennes
64.8k7 gold badges111 silver badges168 bronze badges
asked Apr 21, 2017 at 20:51
8
I’ve done this with AutoHotkey before. This script is tested and working.
I made a basic batch file that will create a «test file» on the desktop.
Just run the AHK file and leave it running. When the script detects a shutdown, it’ll run the batch file.
Make sure you set the path to your text file at the top of the script.
AutoHotkey Script:
;==============================
;Set the path to your batch file.
path := "C:\batch.bat"
;==============================
; Run script as admin. This will allow your batch file to be ran with admin priv.
if not A_IsAdmin
{
Run *RunAs "%A_ScriptFullPath%" ; Requires v1.0.92.01+
ExitApp
}
; Only allow one instance of the script to run.
#SingleInstance, Force
; If you don't want an icon to show in the tray,
; remove the semicolon from the line below.
;#NoTrayIcon
; When script detects WM_QUERYENDSESSION (a shutdown), run OnShutDown function.
OnMessage(0x11, "OnShutDown")
return
OnShutDown(){
; Run the batch file.
Run, % path
ExitApp
}
Batch file I used for testing:
echo Write file before shutdown > %USERPROFILE%\Desktop\ShutdownTest.txt
If you wanted to, you could always execute your batch file commands directly through AHK.
answered Apr 29, 2017 at 4:06
3
Update: If it is something that needs to be done before the next user logs on, putting it in the machine startup script might fulfill your need. If it is something that has to be done before power off, shutdown script is your answer.
If Home edition does not allow you to modify the local policy to make these scripts work, then that is a limitation of the home edition and you may need to upgrade. However, TechNet does not narrow their explanation of how to set up a shutdown script beyond Windows #.
Also, the machine shutdown script will run with permissions of the computer. The user log off script will run with the logged on user’s permissions.
Use a batch script to shut down? Just use the shutdown command («shutdown -t 0») at the end of your shutdown script. Put a shortcut to the script on your desktop, use a power button icon. (Removed answer based on single user shutdown by script instead of start menu shutdown option).
answered Apr 24, 2017 at 14:26
Jeter-workJeter-work
5232 silver badges9 bronze badges
2
I’ve finally found out the solution after several months!
- Open the Group Policy Management Console.
- Then go to
User Configuration\Policies\Windows Settings\Scripts (Logoff)
. - Now add your app or script.
Normally at this point is where it never worked for me.
-
The workaround is to go to
User Configuration\Policies\Administrative Templates\System\Scripts
. -
And enable
Display instructions in shutdown scripts as they run
.
Run GPUPDATE /FORCE
and enjoy!
For shutdown you do the same steps but under Computer Configuration
.
Destroy666
5,6248 gold badges16 silver badges36 bronze badges
answered Jun 28 at 23:40
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
I was wondering if anyone knows how to configure a Windows 7 x64 Enterprise install that is on a domain to run a script if the user attempts to shutdown the computer — but I dont want the script to run if the user tries to log out.
Here is a bit of detail on my situation…
I have installed drive encryption software on 5 desktops that are in use by various people in my group. These desktops are installed a few buildings away in a secure lab that very people have access to. People in my group access these machines (8 Core 2600K Intel Sandybridge with 8GB RAM) over RDP to preform tasks that require heavy lifting that laptops are not well suited for.
I wrote a shutdown script (.hta file) to warn a user that if he/she shuts the computer down, they will have to get access to the lab and enter the drive encryption password in order to bring the machine back online. The script has a timer that counts down for 1 minute and allows the user to cancel the shutdown command.
The script works as expected when a user tries to shutdown the computer, but I just realized that the script seems to run when a user tries to log off. Is there any way to differentiate between a user logging off and a user shutting down a machine? If possible, I would only want the script to run if the machine is shutdown. If the user logs out, I would not want any script to run.
If this is possible, it seems like this would be managed via local Group Policy.
Let me know if you need any further details.
To perform certain customized functions, scripts can be run when Windows Operating System starts or shuts down. The method to execute a script at startup or shutdown varies with different versions. Here’s how to execute scripts at shutdown and startup.
Note: This trick works in Windows XP, Vista and Windows 7 and recent versions, but the method varies depending on your edition.
How to execute a script for professional or full editions of Windows?
Start the policy editor of the local group: Start Menu > Run > Type gpedit.msc
- Under Vista or Windows 10 you can type the command in the search bar of the start menu or press Windows key + R
- Go to Computer Configuration > Windows Settings > Scripts (Startup/Shutdown)
- Depending on what you want, double click on Start or Stop system
- Click Add > Browse and select the script you want to add.
How to execute a script for all editions?
These steps involve modifying the registry. It is therefore recommended to make a backup before proceeding.
- Open notepad and copy the code below:
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0] "GPO-ID"="LocalGPO" "SOM-ID"="Local" "FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine" "DisplayName"="Stratégie de groupe locale" "GPOName"="Stratégie de groupe locale" [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0] "GPO-ID"="LocalGPO" "SOM-ID"="Local" "FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine" "DisplayName"="Stratégie de groupe locale" "GPOName"="Stratégie de groupe locale" [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0] "Script"="C:\\script1.bat" "Parameters"="" "ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
Once you understand the code, you can adapt it to suit your needs by changing some of the variables.
- C:\\script.bat represents the path to your script on the hard disk.
- 0 represents the number of the script in case you have several scripts to run.
- Startup is the time of execution of the script.
It is possible to add multiple scripts:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0] "Script"="C:\\script1.bat" "Parameters"="" "ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
It is also possible to specify parameters for the execution of this script by changing the Parameters field.
Finally, save this text file:
- Go to File > Save.
- Give it a name ending with .reg.
- Select All files in the list box File Type.
- Save the file to the desired location and double click on this file.
Do you need more help with Windows? Check out our forum!