- Create WMI Filters for the GPO
- To create a WMI filter that queries for a specified version of Windows
- To link a WMI filter to a GPO
- Windows 10 Create a WMI Filter for Group Policy
- Problem
- Solution
- Создание WMI фильтров для групповых политик (GPO) в домене AD
- Для чего используются WMI фильтры GPO?
- Как создать новый WMI фильтр и привязать его к GPO?
- Примеры запросов для WMI фильтров GPO
- Тестирование WMI фильтра с помощью PowerShell
Create WMI Filters for the GPO
Applies to
- WindowsВ 10
- Windows Server 2016
To make sure that each GPO associated with a group can only be applied to devices running the correct version of Windows, use the Group Policy Management MMC snap-in to create and assign WMI filters to the GPO. Although you can create a separate membership group for each GPO, you would then have to manage the memberships of the different groups. Instead, use only a single membership group, and let WMI filters automatically ensure the correct GPO is applied to each device.
Administrative credentials
To complete these procedures, you must be a member of the Domain Administrators group, or otherwise be delegated permissions to modify the GPOs.
First, create the WMI filter and configure it to look for a specified version (or versions) of the Windows operating system.
To create a WMI filter that queries for a specified version of Windows
Open the Group Policy Management console.
In the navigation pane, expand Forest: YourForestName, expand Domains, expand YourDomainName, and then click WMI Filters.
Click Action, and then click New.
In the Name text box, type the name of the WMI filter.
Note:В В Be sure to use a name that clearly indicates the purpose of the filter. Check to see if your organization has a naming convention.
In the Description text box, type a description for the WMI filter. For example, if the filter excludes domain controllers, you might consider stating that in the description.
Click Add.
Leave the Namespace value set to root\CIMv2.
In the Query text box, type:
This query will return true for devices running at least WindowsВ Vista and Windows ServerВ 2008. To set a filter for just Windows 8 and Windows Server 2012, use «6.2%». For Windows 10 and Windows Server 2016, use «10.%». To specify multiple versions, combine them with or, as shown in the following:
To restrict the query to only clients or only servers, add a clause that includes the ProductType parameter. To filter for client operating systems only, such as Windows 8 or WindowsВ 7, use only ProductType=»1″. For server operating systems that are not domain controllers, use ProductType=»3″. For domain controllers only, use ProductType=»2″. This is a useful distinction, because you often want to prevent your GPOs from being applied to the domain controllers on your network.
The following clause returns true for all devices that are not domain controllers:
The following complete query returns true for all devices running Windows 10, and returns false for any server operating system or any other client operating system.
Specific versions of Windows 10 can be targeted by including the major build version in the query. The following query returns true for all devices running Windows 10 20H2 (which has a major build version of 19042 ), and returns false for any server operating system or any other client operating system. Additional information about Windows 10 build versions can be found at Windows 10 release information.
The following query returns true for any device running Windows Server 2016, except domain controllers:
Click OK to save the query to the filter.
Click Save to save your completed filter.
If you’re using multiple queries in the same WMI filter, these queries must all return TRUE for the filter requirements to be met and for the GPO to be applied.
To link a WMI filter to a GPO
After you have created a filter with the correct query, link the filter to the GPO. Filters can be reused with many GPOs simultaneously; you do not have to create a new one for each GPO if an existing one meets your needs.
Open the Group Policy Management console.
In the navigation pane, find and then click the GPO that you want to modify.
Under WMI Filtering, select the correct WMI filter from the list.
Click Yes to accept the filter.
Windows 10 Create a WMI Filter for Group Policy
KB ID 0001267
Problem
I was messing around with some GPO’s for client today to replace ‘Edge’ as the default browser, (with IE11). To make the whole process more efficient, I wanted to use a WMI filter toapply the policy only to Windows 10 machines. Before this used to be simple enough, you just set the Windows version in a WMI query. But because it searches for a string e.g. 6.1 (for Windows 8.1), that’s great, and Windows 10 is version 10, so that should be simple yes? Well no, because it’s a string WMI sees the 1 at the beginning, and thinks its lower than 6.1 ‘duh’. You can get around this will a small modification on the search string.
Solution
In the Group Policy Management Console > Forest > Domains >
Query: select * from Win32_OperatingSystem where Version like “10.%” and ProductType=”1″
Note: If you don’t set the ProductType, it will apply to Server 2016 as well.
Copy/Paste Syntax Error: WordPress has a habit of changing the quotes in that command, (above). After pasting it, delete and retype the quotes if you get any syntax errors.
When you click Save don’t worry if you get an error;
Either the namespace entered is not a valid namespace on the local computer or you do not have access to this namespace on this computer. It is possible this is a valid namespace on the remote computer(s). If you wish to use this namespace, press OK. Press cancel to choose another namespace.
I ignored the error above, and it worked fine.
You can now change the policy that you want only to apply to Windows 10, and apply the WMI filter.
How to See If it will work: From within the GPMC console, you can run a group policy results session, to make sure the WMI filter applies as expected.
Создание WMI фильтров для групповых политик (GPO) в домене AD
Технология WMI фильтров в групповых политиках (GPO) позволяет более гибко применять политики на клиентов, за счет использования различных правил, позволяющих указывать WMI запросы для формирования критериев выборки компьютеров, на которые будет действовать групповая политика. К примеру, с помощью WMI фильтров GPO вы можете применить политику, назначенную на OU, только к компьютерам с ОС Windows 10 (на других версиях Windows такая политика с фильтром применяться не будет).
Для чего используются WMI фильтры GPO?
Обычно технология фильтрации групповых политик с помощью WMI (Windows Management Instrumentation) используется в ситуациях, когда объекты домена (пользователи или компьютеры) находятся в плоской структуре AD, а не в выделенном OU, либо если необходимо применить политики, в зависимости от версии ОС, ее сетевых настроек, наличию определенного установленного ПО или любом другом критерии, который можно выбрать с помощью WMI. При обработке такой групповой политики клиентом, Windows будет проверять свое состояние на соответствие указанному WMI запросу на языке WQL (WMI Query Language), и, если условия фильтра выполняются, такая GPO будет применена к компьютеру.
WMI фильтры групповых политик впервые появились еще в Windows XP, и доступны вплоть до последних версий Windows (Windows Server 2019, 2016, Windows 10, 8.1).
Как создать новый WMI фильтр и привязать его к GPO?
Чтобы создать новый WMI фильтр, откройте консоль управления доменными групповыми политиками Group Policy Management (gpmc.msc) и перейдите в раздел Forest -> Domains -> winitpro.ru -> WMI Filters. В этой секции содержатся все WMI фильтры домена. Создайте новый WMI фильтр (New).
В поле Name укажите имя фильтра, в поле Descriptions его описание (не обязательно). Чтобы добавить в фильтр WMI запрос нажмите на кнопку Add, укажите имя пространства имен WMI (по умолчанию root\CIMv2) и укажите код WMI запроса.
WMI запрос имеет следующий формат:
Select * from WHERE
В нашем примере вы хотим создать WMI фильтр, позволяющий применить групповую политику только на компьютеры с Windows 10. Код WMI запроса может выглядеть так:
Select * from Win32_OperatingSystem where Version like «10.%» and ProductType=»1″
Созданные WMI фильтры хранятся в объектах класса msWMI-Som домена Active Directory в разделе DC=…, CN=System, CN=WMIPolicy, CN=SOM их можно найти и отредактировать с помощью консоли adsiedit.msc.
После создания WMI фильтра его можно привязать к конкретному объекту GPO. Найдите нужную политику в консоли GPMC и на вкладке Scope в выпадающем меню секции WMI Filtering выберите созданный ранее WMI фильтр. В этом примере я хочу, чтобы политика автоматического назначения принтеров применялась только к компьютерам с Windows 10.
Дождитесь применения данной политики на клиентов, или обновите ее с помощью gpupdate /force . При анализе примененных политик на клиенте нужно использовать команду gpresult /r. Если политика действует на клиента, но не применяется из-за WMI фильтра, такая политика в отчете будет иметь статус Filtering: Denied (WMI Filter) и указано имя WMI фильтра.
Примеры запросов для WMI фильтров GPO
Рассмотрим различные примеры WMI фильтров GPO, который чаще всего используются.
С помощью WMI фильтра вы можете выбрать тип ОС:
- ProductType=1 – любая клиенская ОС
- ProductType=2 – контроллер домена AD
- ProductType=3 – серверная ОС (Windows Server)
- Windows Server 2016 и Windows 10 — 10.%
- Windows Server 2012 R2 и Windows 8.1 — 6.3%
- Windows Server 2012 и Windows 8 — 6.2%
- Windows Server 2008 R2 и Windows 7 — 6.1%
- Windows Server 2008 и Windows Vista — 6.0%
- Windows Server 2003 — 5.2%
- Windows XP — 5.1%
- Windows 2000 — 5.0%
Вы можете комбинировать условия выборки в WMI запросе с помощью логических операторов AND и OR. Чтобы применить политику только к серверам с Windows Server 2016, код WMI запроса будет таким:
select * from Win32_OperatingSystem WHERE Version LIKE «10.%» AND ( ProductType = «2» or ProductType = «3» )
Выбрать 32 битные версии ОС Windows 8.1:
select * from Win32_OperatingSystem WHERE Version like «6.3%» AND ProductType=»1″ AND OSArchitecture = «32-bit»
Применить политику только к 64-битным ОС:
Select * from Win32_Processor where AddressWidth = «64»
Выбрать Windows 10 с определенным билдом, например Windows 10 1803:
select Version from Win32_OperatingSystem WHERE Version like “10.0.17134” AND ProductType=”1″
Применить политику только к виртуальным машинам VMWare:
SELECT Model FROM Win32_ComputerSystem WHERE Model = “VMWare Virtual Platform”
select * from Win32_SystemEnclosure where ChassisTypes = «8» or ChassisTypes = «9» or ChassisTypes = «10» or ChassisTypes = «11» or ChassisTypes = «12» or ChassisTypes = «14» or ChassisTypes = «18» or ChassisTypes = «21»
WMI фильтр, который применится только к компьютерам, чьи имена начинаются на “msk-pc“(например, для блокировки подключения USB накопителей на этих устройствах):
SELECT Name FROM Win32_ComputerSystem WHERE Name LIKE ‘msk-pc%’
Пример использования WMI фильтра для тонкого нацеливания групповой политики к IP подсетям описывается в статье WMI фильтр для привязки GPO к IP подсети. Например, чтобы применить политику к клиентам в нескольких IP подсетях, используйте фильтр:
Select * FROM Win32_IP4RouteTable WHERE (Mask=’255.255.255.255′ AND (Destination Like ‘192.168.1.%’ OR Destination Like ‘192.168.2.%’))
Применять политику к компьютерам, с количеством оперативной памяти больше 1 Гб:
Select * from WIN32_ComputerSystem where TotalPhysicalMemory >= 1073741824
WMI фильтр проверки наличия на компьютере Internet Explorer 11:
SELECT path,filename,extension,version FROM CIM_DataFile WHERE path=»\\Program Files\\Internet Explorer\\» AND filename=»iexplore» AND extension=»exe» AND version>»11.0″
Тестирование WMI фильтра с помощью PowerShell
При написании WMI запросов иногда нужно получать значения различных параметров на компьютере. Вы помете получить эти данный с помощью командлета Get-WMIObject. Например, выведем атрибуты и значения WMI класса Win32_OperatingSystem:
SystemDirectory : C:\WINDOWS\system32
Organization :
BuildNumber : 17134
RegisteredUser : Windows User
SerialNumber : 00331-10000-00001-AA494
Version : 10.0.17134
Чтобы вывести все доступные параметры класса:
Get-WMIObject Win32_OperatingSystem| Select *
Для тестирования WMI фильтров на компьютерах можно использовать PowerShell. Допустим, вы написали сложный WMI запрос и его хотите проверить (соответствует ли компьютер данному запросу или нет). Например, вы создали WMI фильтр проверки наличия IE 11 на компьютере. На целевом компьютере вы можете выполнить этот WMI запрос с помощью командлета get-wmiobject:
get-wmiobject -query ‘SELECT * FROM CIM_DataFile WHERE path=»\\Program Files\\Internet Explorer\\» AND filename=»iexplore» AND extension=»exe» AND version LIKE «11.%»‘
Если данная команда что-то возвращает, значит компьютер соответствует условиям запроса. Если команда get-wmiobject ничего не вернула — компьютер не соответствует запросу.
Например, запустив указанный запрос на компьютере с Windows 10 и IE 11, команда вернет:
Compressed : False
Encrypted : False
Size :
Hidden : False
Name : c:\program files\internet explorer\iexplore.exe
Readable : True
System : False
Version : 11.0.17134.1
Writeable : True
Это значит, что IE 11 установлен на компьютере и GPO с таким WMI фильтром будет применяться к этому компьютеру.
Итак, мы разобрались как использовать WMI фильтры для применения групповых политик только компьютерам, попадающим под условия запроса. Нужно учитывать наличие WMI фильтров при анализе причин, из-за которых не применяется политика на компьютере.