Как развернуть сценарий power shell в active directory с использованием gpo

Dante Falls

Active Directory and PowerShell Discussing The Upcoming Software Deployment

I want to manage these policies in windows 2019 server which is not part of any domain.

I know the registry keys for the policies but when I add or update this registries I dont see the corresponding changes in the gpedit.msc (gui).

Ron's user avatar

In this article, we will guide you through the process of opening the Local Group Policy Editor on Windows Home. Despite the challenges posed by the absence of this feature in Windows Home editions, we will show you a straightforward method to enable and access it.

Консоль редактора локальных групповых политик в Windows (gpedit.msc) используется для тонкой настройки параметров Windows.
Gpedit.msc
– это стандартная MMC оснастка, доступная во всех версиях Windows (Pro/Enterprise/Education), кроме домашних редакций (Home/Single Language). В этой статье мы рассмотрим особенности использования локального редактора GPO, а также способы установить и запустить gpedit.msc в домашних редакциях Windows 10 и Windows 11 Home.

Step 4. Restart Your Computer

Now restart your computer and when you log back in, you should have a copy of the “deviceName.ps1” file located on your desktop. You should also try running the file to make sure everything works. Reference the image below.

The “deviceName.ps1” File Has Successfully Copied Onto My Domain Controller’s Desktop After Rebooting

It worked! The script was successfully copied onto my desktop when I logged into my domain controller. I also tried running the script, and it was successful.

The PowerShell Script Was Successfully Copied To agaliano Desktop
The “deviceName.ps1” Works As Copied

Why Disable PowerShell?

Step 1: Find the PowerShell.exe file path

By default PowerShell.exe is located in this folder -> C:\Windows\System32\WindowsPowerShell\v1.0

To verify this on your computer, open PowerShell, then open task manager, go to the details tab, scroll down to powershell.exe, right click and select “open file location”.

Как развернуть сценарий power shell в active directory с использованием gpo

Windows explorer will open to the folder location of powershell.exe. Make a note of this location as it will be needed in a later step.

Как развернуть сценарий power shell в active directory с использованием gpo

Step 2: Create GPO to block PowerShell.exe

1. Open the Group Policy Management Console

Как развернуть сценарий power shell в active directory с использованием gpo

Give the new GPO a name. I like to be descriptive with names so it’s easy to understand it.

Как развернуть сценарий power shell в active directory с использованием gpo

You have now created a new GPO, the next step will be to edit the settings.

Now right-click “Software Restriction Policies” and select “New Software Restriction Policies”

Как развернуть сценарий power shell в active directory с использованием gpo

Select “Additional Rules”, then right-click and select “New Path Rule”

Как развернуть сценарий power shell в active directory с использованием gpo

Now click the browse button and select the powershell.exe file from the path in step 1. Most common path is -> C:\Windows\System32\WindowsPowerShell\v1.0.

Set the security level to “Disallowed” Click OK.

Как развернуть сценарий power shell в active directory с использованием gpo
Как развернуть сценарий power shell в active directory с использованием gpo

Step 2. Create Your PowerShell Script(s)

Reference the picture below to see an example of the “deviceName.ps1” script being executed.

The “deviceName.ps1” PowerShell Script Displaying The Computer Name

Creating The PowerShell Script

Open up Notepad and copy the PowerShell script from the image, below. When you are done, save the file to the Desktop as “deviceName.ps1”. This will save your file as a PowerShell script. Remember that PowerShell scripts have a “.ps1” file extension. Reference the image below.

The “deviceName.ps1” PowerShell Script

The lines that begin with “#” are comments and they will not effect what your script does. It is good practice to comment out a few lines in your code and include information about the script itself (Date, Author, Script Language, Purpose, etc.)

The only two lines in our script that are functional are the last two lines:

Add-Type -AssemblyName PresentationFramework

I encourage you to do your own research on what these two lines of PowerShell code do. I will, however, tell you that the “$env:computername” is an environment variable that holds the computer name. That is why you interact with this variable in our script.

Make sure you test your script by right-clicking on the script and choosing “Run with PowerShell”. Below is an example of the code working and displaying the computer name as a pop-up window.

The “deviceName.ps1” Script Successfully Displays The Computer Name
Move Your “deviceName.ps1” Script To Your Share Folder

Step 3. Deploying Our Script With An Active Directory Group Policy Object

We’ve reached the last step of deploying the PowerShell script in our Active Directory domain. Open the “Group Policy Management” tool. Reference the image below.

Open The Group Policy Management Tool
Creating and Linking Our GPO For The PowerShell Script Deployment

We now need to edit our Group Policy Object. Right click on the group policy object that we just made and choose the “Edit” option. The “Group Policy Management Editor” tool will appear, and this is where we will edit our Group Policy Object. The Group Policy Management Editor can be seen in the image below.

:/>  Освойте искусство сравнения баз данных с помощью power shell и db forge studio для sql server
The Group Policy Management Editor
Adding A Script To Our Group Policy Object

Click the “Add” button, and then click “Browse”. Reference the image below.

From here, a file selection window will appear. Copy and paste the “deviceName_deploy.ps1” file from “\\WIN-DC-SERVER\PowerShell_Scripts” into this location. DO NOT change the path, this is the path of the Group Policy Object. Reference the image below for visual instruction.

After copying the script to this location, click “Open” and the file selection window will close. then “Apply” the changes in the next window and click “Okay”. You should see your script added to the PowerShell scripts list in the “Logon Properties” window. Reference the image below for visual instruction.

You have now finished editing the Group Policy Object and can exit out of the “Group Policy Management Editor” tool. However, we now need to go back into the Group Policy Management tool and check one last setting.

The Group Policy Object Security Filtering Should Include Authenticated Users Only

Group Policy Object updates take about 90–120 minutes to take effect. By running the above command, the Group Policy Objects will take effect, immediately. Reference the image below.

Forcing All Group Policy Objects To Update

Answer

Martin Iszac's user avatar

  • Jan 9 at 19:48

  • Hi Ron, got it, have you tried Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit" -Name "ProcessCreationIncludeCmdLine_Enabled" -Value 1 then after that run gpupdate /force for the change to take affect.

    Jan 9 at 20:03

  • Hi Martin, yes I tried this. Command executes successfully but there is no changes in the policy and it is still showing as “Not Configured”.

    Jan 9 at 20:13

  • Jan 9 at 20:22

Настройка Windows с помощью редактора локальных групповых политик

Чтобы запустить редактор локальных групповых политик в Windows, нужно выполнить команду
gpedit.msc

как запустить gpedit.msc в windows 10 или 11

Доступные настройки в консоли редактора локальной GPO представлены в виде древовидной структуры и разделены на две секции:

  • Параметры компьютера (Computer Configuration) – глобальные настройки ОС Windows и компонентов. Вносят изменения в раздел реестра HKEY_LOCAL_MACHINE (HKLM)
  • Параметры пользователей (User configuration) – настройки, которые применяются для пользователей компьютера. Изменения вносятся в ветку реестра пользователя HKEY_CURRENT_USER (HKCU)

внешний вид консоли редактора локальных групповых политики в windows 10 gpedit

В редакторе GPO содержится несколько тысяч настроек Windows, которые расположены в стройной иерархии, имеют подробное описание и предлагают для выбора предопределенные опции настройки.

В каждой секции есть по три подраздела:

  • Software Settings
  • Windows Settings — здесь расположены основные настройки безопасности Windows (в том числе настройки политики паролей, блокировки аккаунтов, политики аудита, назначения прав пользователей)
  • Administrative Templates – настройки различных компонентов и подсистем Windows. Здесь доступны как стандартные административные шаблоны Windows, так и дополнительно установленные ADMX шаблоны групповых политик (например, admx шаблоны для управления программами из пакета MS Office или шаблоны для Google Chrome)

Чтобы изменить любой параметр GPO в консоли, нужно найти раздел, в котором он находится и открыть его настройки в правой панели.

По умолчанию все параметры в разделе административных шаблонов не настроены (Not configured). У большинства настроек GPO доступно есть всего три параметра: Enabled/Disabled/Not configured. По умолчанию все политики не заданы. Вы можете включить или отключить параметр, выбрав Enabled или Disabled, и нажав OK.Если вы хотите вернуть стандартное значение настройки, выберите Not Configured.

изменить настройки GPO с помощью консоли gpedit.msc

У некоторых настроек GPO можно задать дополнительные параметры, которые можно настроить в секции Options. Например, чтобы задать файл обоев рабочего стола через GPO, нужно включить политику (Enabled), указать путь к файлу с рисунков в поле и выбрать стиль рисунка.

дополнительные настройки параметра локальной политики

В поле Help доступно детальное описание каждого параметра GPO. В поле Supported on указаны версий Windows, для которых данная политика применяется. Например, At least Windows 10 означает, что политика применима только к Windows 10/11 и Windows Server 2016/2019/2022. Данный параметр не будет работать на Windows 8.1 или 7.

Настройки, заданные в редакторе gpedit.msc имеют высокий приоритет и перезаписывают любые настройки, заданные пользователем или администратором в графическом интерфейсе Windows или в панели управления.

Редактор локальной GPO хранит настройки примененных параметров в registry.pol файлах в каталогах

  • %SystemRoot%\System32\GroupPolicy 
    – политики компьютера
  • %SystemRoot%\System32\GroupPolicyUsers
    – политики пользователя

Если вы удалите файлы из этих папок, вы сбросите все настройки локальных политик на значения по-умолчанию (Not configured).

В ADMX файлах GPO определяются параметры реестра и их значения, в которые нужно внести изменения. Поэтому фактически, когда вы включили той или иной параметр реестра, обработчик групповых политики внесет изменения в реестр.

Соответствия между названия параметров политик и ключами реестра описываются в Excel документе Windows11andWindowsServer2019PolicySettings—23H2.xlsx, доступном для загрузки с сайта Microsoft. Актуальная версия справочника — Group Policy Settings Reference Spreadsheet for Windows 11 2023 Update 23H2, https://www.microsoft.com/en-us/download/details.aspx?id=105668

How to Enable Group Policy Editor (gpedit. msc) on Windows 10/11 Home Edition?

To enable the Group Policy Editor on Windows Home editions, you can use any method like GPEdit Installer or PowerShell Script to enable the Group Policy Editor on Windows Home edition.

Method 1: Using PowerShell Script

For the more technically inclined, enabling the Group Policy Editor via a script is an efficient way to activate this feature. This method involves executing a script that automates the installation process, providing a swift and direct approach to accessing the Group Policy Editor on Windows Home Editions.

Step 1: Notepad

Step 2: Copy this code and paste it into Notepad and save as it a .bat

dir /b %SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientExtensions-Package~3*.mum >List.txt

dir /b %SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientTools-Package~3*.mum >>List.txt

for /f %%i in (‘findstr /i . List.txt 2^>nul’) do dism /online /norestart /add-package:”%SystemRoot%\servicing\Packages\%%i”

Step 4: After completion, press any key to close the Command Prompt

Step 5: Restart

Method 2: Using GPEdit Installer

Step 1: Download the setup file from this link

Step 2: Double-click on the setup.exe file then click on “next

Step 3: Install

Step 4: After clicking on the install button a window will be pop

Step 5: Restart

Allow PowerShell for Administrators

1. Create a new Active Directory Security group.

Как развернуть сценарий power shell в active directory с использованием gpo

2. Modify GPO Delegation

Now go back to the GPO you created in step 1 and click on the delegation tab.

Как развернуть сценарий power shell в active directory с использованием gpo

In the permissions section make sure the group is selected and it has only these permissions

  • Read is set to “allow”
  • Apply group policy is set to “Deny”
Как развернуть сценарий power shell в active directory с использованием gpo

Step 1. Create A Share Folder

Creating A Parent Folder Called “IT”

Now create a subfolder inside of your “IT” folder and name it “PowerShell_Scripts”. If you copied me exactly, then your final folder path should be:

Reference the image below.

The “C:\IT\PowerShell_Scripts” Subfolder

Now we need to enable sharing on our subfolder settings. Right click the “PowerShell_Scripts” subfolder and click “Properties”. Then click the “Sharing” tab and choose the “Advanced Sharing” option. Reference the image below.

The Advanced Sharing Option For Our Subfolder
Enabling Network Sharing “C:\IT\PowerShell_Scripts”
Remove The “Everyone” Group From Your Folder’s Share Permissions
Add “Domain Computers” and “Domain Users” To Your Share Permissions

Now click “Apply” and “Okay” until you are back at the properties page. From there, click the “Security” tab and we will make some changes here. Reference the image below to locate the “Security” tab.

The “C:\IT\PowerShell_Scripts” Security Properties Tab
Add “Domain Computers” and “Domain Users” To Your Folder’s Security Permissions

When your permissions look like the picture above, you can click “Apply” and then “Okay” and then go back to the “Sharing” tab. Take notice the new Network Path:

This indicates that the folder can now be accessed by other computers in the Network. Let’s test that out on a Windows 10 Client computer that is joined to our Active Directory domain.

Billy Bob Can Successfully Access The “\\WIN-DC-SERVER\PowerShell_Scripts” Share Folder

How to Configure Windows Settings Without the Group Policy Editor ?

You can download Policy Plus from

https://github.com/Fleex255/PolicyPlus

Creating A PowerShell Script For Your PowerShell Script

The “deviceName_deploy.ps1” Script

Once you are done copying the above script, save it as “deviceName_deploy.ps1” and save it to your “C:\IT\PowerShell_Scripts” folder.

Now we will test our script to ensure it works. First, ensure that you do not have a copy of “deviceName.ps1” on your desktop. At this point, both of the PowerShell scripts we have written should ONLY be saved onto the “C:\IT\PowerShell_Scripts” folder. Once you ensure the script is not on your desktop, search for the “\\WIN-DC-SERVER\PowerShell_Scripts” folder and open it.

Inside the folder, locate the “deviceName_deploy.ps1” file and right click it and choose “Run with PowerShell”. If you are prompted to confirm you want to run the command, choose “Y” for yes. If you did everything correctly, your script should now run and copy the “deviceName.ps1” program onto your desktop. Reference the images below if you need help.

“deviceName.ps1” Was Successfully Copied Onto My Desktop

How to Access the Group Policy Editor in Windows Home?

Step 1:WindowsKey + S then on the search bar type “Edit group policy

Step 2: On the right side click on “open

Method 2: Using Run Dialog

Step 1: Windows + R then on run dialog type “gpedit.msc

Step 2:EnterOK to open the group policy on Windows home

Access the Group Policy Editor in Windows – FAQs

How to Open Local Group Policy Editor?

Method 1: Using Search Bar

  1. Windows Key + S and type “Edit group policy
  2. Open” on the right side.

Method 2: Using Run Dialog

  1. Windows Key + R and type “gpedit.msc.
  2. Enter click OK.

How to Open Group Policy Editor in Windows 10?

  1. Windows Key + S and type “Edit group policy
  2. Open

How to Enable Gpedit in Windows 10?

  1. PowerShell scriptGPEdit Installer.
  2. For PowerShell, create a .bat file
  3. GPEdit Installer, download and run the setup file, then restart your computer.

What is the Shortcut for Opening Group Policy Editor?

Windows Key + R, type “gpedit.msc,” and press Enter

How do I open Group Policy Editor in Windows 10 Home?

After enabling the Group Policy Editor as described, press Win + R to open the Run dialog,gpedit.msc, and press Enter to open it.

How to edit local group policy with cmd?

You can edit local group policy objectscommand line by directly modifying the Windows Registry, where policy settings are stored. Apply new policies using a .reg file and implement them with the command regedit.exe /s “full path to your .reg file“. Alternatively, use PowerShell scriptsRegistry files XML for importing into Group Policy Preferences.

Установка редактора локальной политики gpedit.msc в Windows 10/11 Домашняя

Консоль редактора локальной GPO отсутствует в домашних редакциях Windows (Home и Single Language). При попытке открыть MMC консоль редактора, появится ошибка:

 Не удается найти gpedit.msc. Проверьте, правильно ли указано имя и повторите попытку.

Не удается найти gpedit.msc в Windows 10 домашняя

Есть обходной недокументированный способ установки редактора gpedit.msc в Windows 10 или 11 Home из хранилища пакетов Windows. Откройте командную строку (cmd.exe) с правами администратора и выполните две следующие команды:

FOR %F IN ("%SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientTools-Package~*.mum") DO (DISM /Online /NoRestart /Add-Package:"%F")
FOR %F IN ("%SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientExtensions-Package~*.mum") DO (DISM /Online /NoRestart /Add-Package:"%F")

установка gpedit.msc в Windows 10 Home через DISM пакетом Microsoft-Windows-GroupPolicy-ClientExtensions-Package

DISM выполните установку пакетов ClientTools и ClientExtensions из внутреннего хранилища Windows. Если у вас установлен другой язык, например русский, также будут установлены пакеты с ru-RU:

Теперь вы сможете запустить консоль gpedit.msc в домашней версии Windows.

запуск редактора gpo gpedit.msc в windows 10 и windows 11

Однако, после редактирования политик, настройки сразу не будут применяться к реестру, как в Pro/Enterprise редакции. Здесь не поможет ни выполнение команды gpupdate /force, ни перезагрузка компьютера. Дело в том, что домашней редакции Windows отсутствует обработчик GPO, который применяет настройки из registry.pol файла в реестр. Для автоматического применения GPO придется обновить редакцию Windows с Home до Pro, но это не всегда возможно.

К счастью, есть обходной способ применения настроек GPO в Windows Home с помощью сторонней утилиты Policy Plus (https://github.com/Fleex255/PolicyPlus). Policy Plus – это альтернативный редактор GPO для Windows. Он позволяет редактировать настройки локальной GPO без использования консоли gpedit.

Policy Plus как альтернативу редактора политик gpedit.msc

Чтобы применить настройки из локальных групповых политики из POL файлов, закройте MMC оснастку gpedit.msc и выберите в Policy plus параметр File -> Save Policy.

Применить локальные политики в домашней версии Windows с помощью утилиты Policy Plus

Должно появится сообщение:

User policies: saved to disk and applied diff to Registry.
Computer policies: saved to disk and applied diff to Registry.

Policy plus заагрузила настройка из файла политик registry.pol в реестр

Оставьте комментарий