- Running PowerShell Startup (Logon) Scripts Using GPO
- Configuring PowerShell Startup Scripts with Group Policy
- Запуск PowerShell скриптов с помощью GPO
- Запуск PowerShell скрипта при загрузке компьютера с помощью групповой политики
- Using Startup, Shutdown, Logon, and Logoff Scripts in Group Policy
- How to set up scripts on the domain controller
- To set up scripts on the domain controller
- How to assign computer startup scripts
- To assign computer startup scripts
- How to assign computer shutdown scripts
- To assign computer shutdown scripts
- How to assign user logon scripts
- To assign user logon scripts
- How to assign user logoff scripts
- To assign user logoff scripts
Running PowerShell Startup (Logon) Scripts Using GPO
Group Policy allows you to run various script files at a computer startup/shutdown or during user logon/logout. You can use GPOs not only to run classic batch files on a domain computers (.bat, .cmd, .vbs), but also to execute PowerShell scripts (.ps1) during Startup/Shutdown/Logon/Logoff.
In modern operating systems (Windows 10 / Windows Server 2016), you can configure the logon/startup PowerShell scripts directly from the domain GPO editor.
Run the domain policy management console – GPMC.msc (Group Policy Management), create a new policy and link it to the desired Active Directory container (OU) with users or computers (you can use WMI GPO filters for fine policy targeting). Switch to policy Edit mode.
You must select a GPO section to run the PowerShell script, depending on when you want to execute your PS1 script:
- If you want to run a PS script when a user logon (logoff) to a computer (to configure user’s environment settings, programs, for example: you want to automatically generate an Outlook signature based on the AD user properties, adjust screensaver or Start layout settings), you need to go to the GPO section: User Configuration -> Policies -> Windows Settings -> Scripts (Logon / Logoff);
- If you want to run the PowerShell script at a computer startup (to disable outdated protocols: NetBIOS and LLMNR, SMBv1, configure computer security settings, etc.) or before the computer shutdown, you need to go to the GPO section with the computer settings: Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown).
Configuring PowerShell Startup Scripts with Group Policy
Suppose, we have to run the PowerShell script at a computer startup. Select the Startup policy, and go to the PowerShell Scripts tab in the next window.
Now you need to copy the file with your PowerShell script to the domain controller. Click the Show Files button and drag the file with the PowerShell script (ps1 extension) into the opened File Explorer window (the console will automatically open the folder \\yourdomainname\SysVol\yourdomainname\Policies\
Since we configure the Startup PowerShell script, you need to check the NTFS “Read&Execute” permissions for the Domain Computers group in the ps1 file permissions (or check the permissions on the entire Machine\Scripts\Startup folder).
Now click Add and add the copied .PS1 script file to the list of scripts to be run by the PowerShell policy.
If you run multiple PowerShell scripts through a GPO, you can control the order in which the scripts are executed using the Up/Down buttons.
To correctly run PowerShell scripts during computer startup, you need to configure the delay time before scripts launch using the policy in the Computer Configuration -> Administrative Templates -> System -> Group Policy section. Enable the “Configure Logon Script Delay” policy and specify a delay in minutes before starting the logon scripts (sufficient to complete the initialization and load all necessary services). It is usually enough to set up here for 1-2 minutes.
By default, Windows security settings do not allow running PowerShell scripts. The current value of the PowerShell script execution policy setting can be obtained using the Get-ExecutionPolicy cmdlet. If the policy is not configured, the command will return Restricted (any scripts are blocked). The security settings for running the PowerShell script can be configured via the “Turn On Script Execution” policy (in the GPO Computer Configuration section -> Administrative Templates -> Windows Components -> Windows PowerShell). Possible policy values:
- Allow only signed scripts (AllSigned) – you can run only signed PowerShell scripts (“How to digitally sign a PowerShell script?”) — this is the best option from a security perspective;
- Allow local scripts and remote signed scripts (RemoteSigned) – you can run any local and signed remote scripts;
- Allow all scripts (unrestricted) – the most insecure option, because allows executing any PowerShell scripts.
If not one of the setting of the PowerShell scripts execution policy is suitable for you, you can run PowerShell scripts in the Bypass mode (scripts are not blocked, warnings do not appear).
To do this, the PowerShell script must be run from the Startup -> Scripts section. In this section, you can configure ps1 script to run by creating the usual Startup batch file that runs the powershell.exe executable file (similar to the script described in the article). Specify:
- Script Name: %windir%\System32\WindowsPowerShell\v1.0\powershell.exe
- Script Parameters: -Noninteractive -ExecutionPolicy Bypass –Noprofile -file %
dp0 when launched on the client is automatically converted to the UNC path to the script directory on SYSVOL.
As you can see, in this case you allowed running untrusted PoSh scripts by specifying Bypass parameter of the ExecutionPolicy.
Запуск PowerShell скриптов с помощью GPO
Групповые политики Window позволяют запускать различные файлы скриптов при загрузке/ завершении работы компьютера, входе/выходе пользователя. С помощью GPO вы можете исполнять на компьютерах домена не только классические файлы скриптов (.bat, .cmd, ,vbs), но и Startup/Shutdown/Logon/Logoff скрипты PowerShell (.ps1)
В современных операционных системах (Windows 10 / Windows Server 2016) вы можете настраивать запуск логон/логоф скриптов на PowerShell напрямую из редактора GPO.
Запустите консоль управления доменными политиками — GPMC.msc (Group Policy Management сonsole), создайте новую политику и назначьте ее на нужный контейнер с пользователями или компьютерами (можно использовать WMI фильтры GPO для более тонкого нацеливания политики). Перейдите в режим редактирования политики.
Вы должны выбрать раздел GPO для запуска PowerShell скрипта в зависимости от того, когда вы хотите выполнить ваш скрипт.
- Если PS скрипт должен быть запущен при входе пользователя на компьютер (настройка параметров окружения пользователя, программ, например: вы хотите при входе пользователя автоматическое создавать подпись в Outlook на основе данных из пользователя AD, настроить параметры экранной заставки или стартового экрана) или при выходе пользователя, вам нужно перейти в раздел GPO: UserConfiguration-> Policies-> WindowsSettings-> Scripts(Logon/ Logoff);
- Если вы хотите запускать скрипт PowerShell при загрузке компьютера (отключение устаревших протоколов: NetBIOS, SMBv1, настройка параметров безопасности компьютера и т.д.) или перед корректным выключением компьютера, вам нужно перейти в секцию GPO с настройками компьютера: Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown).
Запуск PowerShell скрипта при загрузке компьютера с помощью групповой политики
Допустим, нам нужно запускать PowerShell скрипт при загрузке Windows. Для этого нужно выбрать Startup и в открывшемся окне перейди на вкладку PowerShell Scripts.
Теперь нужно скопировать файл с вашим PowerShell скриптом на контроллер домена. Нажмите на кнопку Show Files и перетяните файл с PowerShell скриптом (расширение ps1) в открывшееся окно проводника (консоль автоматически откроет каталог \\yourdomain\SysVol\yourdomain\Policies\<Здесь_GUID_вашей_GPO>\Machine\Scripts\Startup вашей политики в каталоге SysVol на ближайшем контроллере домена).
Т.к. мы настраиваем запуск Startup скрипта PowerShell, нужно в разрешениях ps1 файла (или всего каталога Machine\Scripts\Startup) проверить NTFS права доступа на чтение и выполнение (Read & Execute) для группы Domain Computers .
Теперь нужно нажать кнопку Add и добавить скопированный файл скрипта ps1 в список запускаемых политикой PowerShell скриптов.
Если вы запускаете несколько PowerShell скриптов через GPO, вы можете управлять порядком из запуска с помощью кнопок Up/Down.
Для корректного выполнения скриптов PowerShell при загрузке компьютера нужно настроить время задержки перед запуском с помощью политики в разделе Computer Configuration -> Administrative Templates -> System -> Group Policy. Включите политику Configure Logon Script Delay (Настроить задержку сценария входа в систему) и укажите задержку в минутах перед запуском логон-скриптов (достаточное для окончании инициализациии и загрузки всех необходимых служб). Обычно достаточно поставить здесь 1-2 минуты.
По умолчанию в настройках безопасности Windows запрещен запуск PowerShell скриптов. Значение текущей настройки политики запуска сценариев PowerShell можно получить командой Get-ExecutionPolicy. Если политика не настроена, команда вернет Restricted (блокируются любые скрипты). Параметры безопасности запуска PowerShell скриптом можно настроить через политику “Включить выполнение сценариев” / “Turn On Script Execution” (в разделе GPO Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell). Возможные значения политики:
- Allowonlysignedscripts (AllSigned)– можно запускать только подписанные скрипты PowerShell (“Как подписать скрипт PowerShell?”) –самый лучший сценарий с точки зрения безопасности;
- Allowlocalscriptsandremotesignedscripts (RemoteSigned)– можно запускать любые локальные и подписанные удаленные скрипты ;
- Allowallscripts (unrestricted) – самый небезоапасный вариант, т.к. разрешает запуск любых PowerShell скриптов.
Если вам не подходит не один из предложенных сценариев настройки политики запуска PowerShell скриптов, вы можете запускать PowerShell скрипты в режиме Bypass (скрипты не блокируются, предупреждения не появляются).
Для этого PowerShell скрипт нужно запускать из секции Startup -> Scripts. В этой секции вы можете настроить запуск ps1 сценария с помощью создания обычного Startup скрипта, запускающего исполняемый файл powershell.exe (по аналогии со сценарием, описанным в статье). Укажите:
- Script name: %windir%\System32\WindowsPowerShell\v1.0\powershell.exe
- Script Parameters: -Noninteractive -ExecutionPolicy Bypass –Noprofile -file %
dp0 при запуске на клиенте автоматически преобразуются в UNC путь до каталога со скриптом на SYSVOL.
В данном случае вы принудительно разрешили запуск любого (даже ненадежного) скрипта PowerShell с помощью параметра Bypass.
Using Startup, Shutdown, Logon, and Logoff Scripts in Group Policy
This topic contains procedures for using the GPMC tool to configure and run four types of Group Policy.
This topic describes how to install and use scripts on a domain controller. If you want information about script use for the local computer, see Working with startup, shutdown, logon, and logoff scripts using the Local Group Policy Editor.
Group Policy allows you to associate one or more scripting files to four triggered events:
You can use Windows PowerShell scripts, or author scripts in any other language supported by the client computer. Windows Script Host (WSH) supported languages and command files are also used, including VBScript and Jscript.
How to set up scripts on the domain controller
To set up scripts on the domain controller
- Copy the script and dependent files to the Netlogon shared folder on the domain controller.
Additional considerations
You must be a member of the Domain Administrators security group to configure scripts on a domain controller.
How to assign computer startup scripts
To assign computer startup scripts
Open the Group Policy Management Console (GPMC). Right-click the Group Policy Object you want to edit, and then click Edit.
In the console tree, click Scripts (Startup/Shutdown). The path is Computer Configuration\Policies\Windows Settings\Scripts (Startup/Shutdown).
In the results pane, double-click Startup.
In the Startup Properties dialog box, click Add.
In the Add a Script dialog box, do the following:
In Script Name, type the path of the script, or click Browse to search for the script file in the Netlogon shared folder on the domain controller.
In Script Parameters, type any parameters that you want, exactly as you would type them on the command line. For example, if your script includes parameters called //logo (display banner) and //I (interactive mode), type //logo //I.
In the Startup Properties dialog box, specify the options that you want:
Startup Scripts for : Lists all the scripts that currently are assigned to the selected GPO. If you assign multiple scripts, the scripts are processed in the order that you specify. To move a script up in the list, click it, and then click Up. To move a script down in the list, click it, and then click Down.
Add: Opens the Add a Script dialog box, where you can specify any additional scripts to use.
Edit: Opens the Edit Script dialog box, where you can change script information, such as name and parameters.
Remove: Removes the selected script from the Startup Scripts list.
Show Files: Displays the script files that are stored in the selected GPO.
Additional considerations
Startup scripts are run under the Local System account, and they have the full rights that are associated with being able to run under the Local System account.
Startup scripts are run asynchronously, by default.
Setting startup scripts to run synchronously may cause the boot process to run slowly.
Startup scripts that run asynchronously will not be visible. Enabling the Run Startup Scripts Visible Group Policy setting has no effect when you are running startup scripts asynchronously.
How to assign computer shutdown scripts
To assign computer shutdown scripts
Open the Group Policy Management Console. Right-click the Group Policy object you want to edit, and then click Edit.
In the console tree, click Scripts (Startup/Shutdown). The path is Computer Configuration\Policies\Windows Settings\Scripts (Startup/Shutdown).
In the results pane, expand Shutdown.
In the Shutdown Properties dialog box, click Add.
In the Add a Script dialog box, do the following:
In Script Name, type the path of the script, or click Browse to search for the script file in the Netlogon shared folder on the domain controller.
In Script Parameters, type any parameters that you want, exactly as you would type them on the command line. For example, if your script includes parameters called //logo (display banner) and //I (interactive mode), type //logo //I.
In the Shutdown Properties dialog box, specify the options that you want:
Shutdown Scripts for : Lists all the scripts that are currently assigned to the selected Group Policy object (GPO). If you assign multiple scripts, the scripts are processed in the order that you specify. To move a script up in the list, click it, and then click Up. To move a script down in the list, click it, and then click Down.
Add: Opens the Add a Script dialog box, where you can specify any additional scripts to use.
Edit: Opens the Edit Script dialog box, where you can change script information, such as name and parameters.
Remove: Removes the selected script from the Shutdown Scripts list.
Show Files: Displays the script files that are stored in the selected GPO.
Additional considerations
Shutdown scripts are run as Local System, and they have the full rights that are associated with being able to run as Local System.
Setting shutdown scripts to run synchronously may cause the shutdown process to run slowly.
How to assign user logon scripts
To assign user logon scripts
Open the Group Policy Management Console. Right-click the Group Policy object you want to edit, and then click Edit.
In the console tree, click Scripts (Logon/Logoff). The path is User Configuration\Policies\Windows Settings\Scripts (Logon/Logoff).
In the results pane, expand Logon.
In the Logon Properties dialog box, click Add.
In the Add a Script dialog box, do the following:
In Script Name, type the path of the script, or click Browse to search for the script file in the Netlogon shared folder on the domain controller.
In Script Parameters, type any parameters that you want, exactly as you would type them on the command line. For example, if your script includes parameters called //logo (display banner) and //I (interactive mode), type //logo //I.
In the Logon Properties dialog box, specify the options that you want:
Logon Scripts for : Lists all the scripts that currently are assigned to the selected Group Policy object (GPO). If you assign multiple scripts, the scripts are processed in the order that you specify. To move a script up in the list, click it, and then click Up. To move a script down in the list, click it, and then click Down.
Add: Opens the Add a Script dialog box, where you can specify any additional scripts to use.
Edit: Opens the Edit Script dialog box, where you can change script information, such as name and parameters.
Remove: Removes the selected script from the Logon Scripts list.
Show Files: Displays the script files that are stored in the selected GPO.
Additional considerations
Setting logon scripts to run synchronously may cause the logon process to run slowly.
Logon scripts are run as User, not Administrator, and their rights are limited accordingly.
How to assign user logoff scripts
To assign user logoff scripts
Open the Group Policy Management Console. Right-click the Group Policy object you want to edit, and then click Edit.
In the console tree, click Scripts (Logon/Logoff). The path is User Configuration\Policies\Windows Settings\Scripts (Logon/Logoff).
In the results pane, expand Logoff.
In the Logoff Properties dialog box, click Add.
In the Add a Script dialog box, do the following:
In Script Name, type the path of the script, or click Browse to search for the script file in the Netlogon shared folder on the domain controller.
In Script Parameters, type any parameters that you want, exactly as you would type them on the command line. For example, if your script includes parameters called //logo (display banner) and //I (interactive mode), type //logo //I.
In the Logoff Properties dialog box, specify the options the you want:
Logoff Scripts for : Lists all the scripts that currently are assigned to the selected Group Policy object (GPO). If you assign multiple scripts, the scripts are processed in the order that you specify. To move a script up in the list, click it, and then click Up. To move a script down in the list, click it, and then click Down.
Add: Opens the Add a Script dialog box, where you can specify any additional scripts to use.
Edit: Opens the Edit Script dialog box, where you can change script information, such as name and parameters.
Remove: Removes the selected script from the Logoff Scripts list.
Show Files: Displays the script files that are stored in the selected GPO.
Additional considerations
Logoff scripts are run as User, not Administrator, and their rights are limited accordingly.
Setting logoff scripts to run synchronously may cause the logoff process to run slowly.