Windows script at windows logon

How to assign a logon script to a profile for a local user

This article describes how to assign a logon script to a profile for a local user.

Original product version: В Windows Server 2012 R2
Original KB number: В 324803

Summary

This article describes how to assign a logon script to a profile for a local user’s account in Windows Server 2003. This logon script runs when a local user logs on locally to the computer. This logon script does not run when the user logs on to the domain.

You must be logged on as Administrator or as a member of the Administrators group to complete this procedure. If your computer is connected to a network, network policy settings may also prevent you from completing this procedure.

How to assign a logon script to a user’s profile

Click the Start, point to Administrative Tools, and then click Computer Management.

In the console tree, expand Local Users and Groups, and then click Users.

In the right pane, right-click the user account that you want, and then click Properties.

Click the Profile tab.

In the Logon script box, type the file name (and the relative path, if necessary) of the logon script.

If the logon script is stored in a subfolder of the default logon script path, put the relative path to that folder in front of the file name. For example, if the Startup.bat logon script is stored in \\ComputerName\Netlogon\FolderName, type FolderName\Startup.bat .

Click Apply, and then click OK.

Logon scripts that are stored on the local computer apply only to users who log on to the local computer.

Local logon scripts must be stored in a shared folder that uses the share name of Netlogon, or be stored in subfolders of the Netlogon folder.

The default location for local logon scripts is the Systemroot\System32\Repl\Imports\Scripts folder. This folder is not created on a new installation of Windows. Therefore, the SystemRoot\System32\Repl\Imports\Scripts folder must be created and shared out by using the Netlogon share name.

If you do not want to create the Netlogon share in the default location, put the logon script in any folder that the user can access during logon, and then share this folder.

Запуск 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 .

Читайте также:  Прокси клиент для mac os

Теперь нужно нажать кнопку 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.

How to run a logon script one time when a new user logs on in Windows Server 2003

This article describes how to configure a logon script or program to run one time when a user signs in to a computer for the first time.

Original product version: В Windows Server 2003
Original KB number: В 325347

Summary

This article contains information about modifying the registry. Before you modify the registry, make sure to back it up and make sure that you understand how to restore the registry if a problem occurs. For information about how to back up, restore, and edit the registry, see Windows registry information for advanced users.

These steps apply only to new users who have never logged on to the computer. If a user already has a local user profile or a roaming profile, the script or program doesn’t run.

Configure a script to run one time when a new user signs in

If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.

When a Windows Server 2003-based product is installed, the Default User profile is created. The first time that a user logs on, the Default User profile is copied to the user’s profile.

To configure a script or program to run when a new user logs on, follow these steps:

Select Start, and then select Run.

In the Open box, type regedit.exe, and then select OK.

Locate the following subkey in the registry:
HKEY_USERS

On the File menu, select Load Hive.

In the Load Hive dialog box, locate the Profilepath \Default User\Ntuser.dat file, where Profilepath is the file system location of the Default User profile. Select Open.

In the Load Hive dialog box type a name for the hive, and then select OK.

The Ntuser.dat file is hidden. If you can’t locate or load the Ntuser.dat file, you must change your view settings in Windows Explorer. To do it, follow these steps:

  1. Select Start, and then select Windows Explorer.
  2. Select Tools, and then select Folder Options.
  3. Select the View tab.
  4. Click to clear the Hide extensions for known file types check box.
  5. Select Show hidden files and folders, and then select OK.
  • Locate the following subkey in the registry: HKEY_USERS\Test\Software\Microsoft\Windows\CurrentVersion\Runonce

    Where Test is the name that you gave to the Ntuser.dat hive in step 6.

    On the Edit menu, point to New, and then select String Value.

    In the right pane, double-click the new value.

    In the Edit String dialog box, type the full path and file name for the program or logon script, and then select OK.

    In the left pane, select the Test hive.

    On the File menu, select Unload Hive.

    Select Yes when prompted to confirm you want to unload the hive.

    Quit Registry Editor. This program or logon script runs for a user who doesn’t have a user profile. To view the user profiles on the local computer, follow these steps:

    1. Select Start, point to Control Panel, and then select System.
    2. Select the Advanced tab.
    3. In the User Profiles area, select Settings.
      The user profiles are listed in the User Profiles dialog box.
  • —>

    Working with startup, shutdown, logon, and logoff scripts using the Local Group Policy Editor

    This topic describes how to use the Local Group Policy Editor (gpedit) to manage four types of event-driven scripting files.

    Introduction

    Group Policy allows you to associate one or more scripting files with 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 are also used, including VBScript and Jscript. For more information about the editor, see Local Group Policy Editor.

    Additional considerations

    For more information about scripting, see the Group Policy Script Center (https://go.microsoft.com/fwlink/?LinkID=66013).

    Local Group Policy Editor and the Resultant Set of Policy snap-in are available in Windows Server 2008 R2 and Windows 7 Professional, Windows 7 Ultimate, and Windows 7 Enterprise. For more information, see https://go.microsoft.com/fwlink/?LinkId=139815.

    How to assign computer startup scripts

    To assign computer startup scripts

    Open the Local Group Policy Editor.

    In the console tree, click Scripts (Startup/Shutdown). The path is Computer Configuration\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 the Script Name box, type the path to the script, or click Browse to search for the script file in the Netlogon shared folder on the domain controller.

    In the Script Parameters box, type any parameters that you want, the same way 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 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 modify 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

    To complete this procedure, you mustВ have Edit setting permission to edit a GPO. By default, members of the Domain Administrators security group, the Enterprise Administrators security group, or the Group Policy Creator Owners security groupВ have Edit setting permission to editВ a GPO.

    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.

    Beginning in WindowsВ Vista, startup scripts are run asynchronously, by default. This is a different behavior from earlier operating systems.

    Setting startup scripts to run synchronously may cause the boot process to run slowly.

    In WindowsВ 7 and WindowsВ Vista, startup scripts that are run asynchronously will not be visible. Enabling the Run Startup Scripts Visible policy setting will have no effect when running startup scripts asynchronously.

    Local Group Policy Editor and the Resultant Set of Policy snap-in are available in Windows Server 2008 R2 and Windows 7 Professional, Windows 7 Ultimate, and Windows 7 Enterprise. For more information, see https://go.microsoft.com/fwlink/?LinkId=139815.

    How to assign computer shutdown scripts

    To assign computer shutdown scripts

    Open the Local Group Policy Editor.

    In the console tree, click Scripts (Startup/Shutdown). The path is Computer Configuration\Windows Settings\Scripts (Startup/Shutdown).

    In the results pane, double-click 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 to 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, the same way 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 modify 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

    To complete this procedure, you mustВ have Edit setting permission to edit a GPO. By default, members of the Domain Administrators security group, the Enterprise Administrators security group, or the Group Policy Creator Owners security groupВ have Edit setting permission to editВ a GPO.

    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.

    Local Group Policy Editor and the Resultant Set of Policy snap-in are available in Windows Server 2008 R2 and Windows 7 Professional, Windows 7 Ultimate, and Windows 7 Enterprise. For more information, see https://go.microsoft.com/fwlink/?LinkId=139815.

    How to assign user logon scripts

    To assign user logon scripts

    Open the Local Group Policy Editor.

    In the console tree, click Scripts (Logon/Logoff). The path is User Configuration\Windows Settings\Scripts (Logon/Logoff).

    In the results pane, double-click 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 to 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, the same way 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 modify 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

    To complete this procedure, you mustВ have Edit setting permission to edit a GPO. By default, members of the Domain Administrators security group, the Enterprise Administrators security group, or the Group Policy Creator Owners security groupВ have Edit setting permission to editВ a GPO.

    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.

    Local Group Policy Editor and the Resultant Set of Policy snap-in are available in Windows Server 2008 R2 and Windows 7 Professional, Windows 7 Ultimate, and Windows 7 Enterprise. For more information, see https://go.microsoft.com/fwlink/?LinkId=139815.

    How to assign user logoff scripts

    To assign user logoff scripts

    Open the Local Group Policy Editor.

    In the console tree, click Scripts (Logon/Logoff). The path is User Configuration\Windows Settings\Scripts (Logon/Logoff).

    In the results pane, double-click 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 to 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, the same way 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 modify 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

    To complete this procedure, you mustВ have Edit setting permission to edit a GPO. By default, members of the Domain Administrators security group, the Enterprise Administrators security group, or the Group Policy Creator Owners security groupВ have Edit setting permission to editВ a GPO.

    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.

    Читайте также:  Посмотреть свойства системы linux mint
    Оцените статью