Table of Contents
- Scenario
- Digging for the Roots
- Solutions
I ran into a situation similar to the scenario below; although, I caught the problem during testing and not the production implementation. I was faced with a decision to rework my code, or understand the error so I could address it effectively. In this article
I will elaborate on what I found to be the cause of this error, and what situation brings it about. I will then show you what to do about it without having to revert to older methodologies to handle your task.
Scenario
If you have been working in an Active Directory environment for any length of time, there is a good possibility that you have run into a situation where you needed to run some process against all, or at least a large portion, of your Users or Computers.
Managing each account individually is very time consuming and inefficient, so you turn to the almighty PowerShell to automate this process. You start by using Get-ADUser or Get-ADComputer to retrieve the Objects you want from AD, then you use the powerful
Pipeline of PowerShell to send those AD Objects to another cmdlet to do the additional work you need. You may even take the results of the secondary cmdlet and use the pipeline to send them to tertiary, and quaternary cmdlets. The pipeline makes this all very
easy. You’ve tested your process on a few objects and are ready to process against your entire domain. Your change control is approved, you are in the driver’s seat, and you hit the enter button. This wonderful process takes off; it’s pure magic. Flying along,
PowerShell is processing each object and doing exactly what it was designed to do, but you have thousands of objects so this is going to take a while. Your part has been done, you created the process and kicked it off. PowerShell is doing its part, running
your creation. Might as well go to the kitchen and warm up some leftover pizza and grab a nice cold Dr Pepper. You glance over at your laptop on your way to the La-Z-Boy and see that everything is running smoothly, so you flip on an old rerun of Gilligan’s
Island. You watch as they put together some crazy contraption, which in the end utterly fails. If only they had you and PowerShell, they would be home sipping their own Dr Peppers by the end of the show. You glance back over at your laptop and the unthinkable
has occurred. In your PowerShell console where your process should be running, you see this:
get-aduser : The server has returned the following error: invalid enumeration context.
At line:1 char:1
+ get-aduser -Filter {msExchRecipientTypeDetails -eq «2147483648» -AND -NOT(UserAc .
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : The server has returned the following error: invalid enumeration context.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
What happened? A quick web search of «The server has returned the following error: invalid enumeration context.» returns lots of content on the topic with two prevailing recommendations.
- One of the attributes being queried is not indexed in AD. You can resolve this by modifying the Attribute in the AD Schema enabling the index flag.
- Ditch get-aduser and get-adcomputer and use ADSI DirectorySearcher instead.
IE:
https://social.technet.microsoft.com/Forums/scriptcenter/en-US/e3ae9c0d-4eed-4703-b120-14727e797df9/invalid-enumeration-context-using-powershell-script-to-check-computer-accounts?forum=ITCG
You don’t really want to manually modify your Active Directory schema, but this process is important so you give it a shot. Looking at all of the attributes you are pulling you notice that they are all already indexed, or you enable indexing but the problem
persists. You really like using native PowerShell functionality and you don’t really want to rework your code to use ADSI DirectorySearcher, but you really have no other options right? Wrong!
Digging for the Roots
In order to find a solution to this error, we have to understand why it happens in the first place. Let’s don our troubleshooting hat and see what’s going on. We will start by looking at the error message itself.
Note: for the purpose of the below illustration, I will only talk about Get-ADUser, but the same applies to Get-ADComputer.
The error message gives clear indication that the cmdlet which threw the error was Get-ADUser. Since our process is using Get-ADUser to send objects down the pipeline to other cmdlets, we run the Get-ADUser cmdlet by itself to see if we can get any new info.
Surprisingly the Get-ADUser command completes with no errors, and fairly quickly; however, every time we run the cmdlet and pass objects to other cmdlets through the pipeline, we generate the error. That is interesting because Get-ADUser is supposed to just
get the full results and hand them down the pipeline as soon as they come in right? Well, let’s see.
What can we find out about how Get-ADUser works? If we look at the help of Get-ADUser, we see two parameters that are of interest.
-ResultPageSize <int>
Specifies the number of objects to include in one page for an Active Directory Domain Services query.
The
default
is
256
objects per page.
The following example shows how to set this parameter.
-ResultSetSize <System.Nullable[System.Int
32
]>
Specifies the maximum number of objects to return for an Active Directory Domain Services query. If you want to receive
all
of the objects, set this parameter to $null (null value). You can use Ctrl+c to stop the query and return of objects.
The following example shows how to set this parameter so that you receive
all
of the returned objects.
-ResultSetSize $null
So based on these parameters, we know that by default, Get-ADUser will return all matched objects from Active Directory, but it will do it in pages consisting of 256 objects per page.
Side Note: What exactly is paging? Simply put, it’s breaking a large query result down into smaller more manageable pieces. By default, if a Query results in 1000 objects, rather than sending all 1000 object back to the client, the server will send 256
object at a time (in separate pages) until all objects are sent. 1000 objects would result in 4 pages. It is up to the client to tell the server when it is ready for the next page of results.
(Paging Search Results: https://msdn.microsoft.com/en-us/library/aa367011(v=vs.85).aspx)
Now let’s look at Get-ADUser in action.
Using the sysinternals tool, TCPView.exe, we monitor the TCP communication of our Get-ADUser cmdlet while using Measure-Command to capture our runtime.
PS C:> Measure-Command -Expression {get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop}
Days :
0
Hours :
0
Minutes :
0
Seconds :
28
Milliseconds :
904
Ticks :
289045151
TotalDays :
0.000334542998842593
TotalHours :
0.00802903197222222
TotalMinutes :
0.481741918333333
TotalSeconds :
28.9045151
TotalMilliseconds :
28904.5151
From the results we see that it took us 28.9 seconds to get 14.79 MBytes (15,504,491 Rcvd Bytes) of returned data from our query. We also see that we are connecting to TCP port 9389 on our domain controller. A quick web search on this TCP port reveals that
this is the port used by Active Directory Web Services (http://www.t1shopper.com/tools/port-number/9389/).
In order to see how many return objects we are dealing with, we run the command again, piping the results into Measure-Object
PS C:> get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop | Measure-Object
Count :
14163
The first thing we notice is that our process does not error out this time, even though we are using the pipeline. So maybe the problem relates to how long it takes to process our other pipeline commands. Since Measure-Object takes very little time to process,
it does not result in the error being generated. In order to test this theory we will use start-sleep to inject some processing time down the pipeline.
PS C:> get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop | ForEach-Object {Start-Sleep -Milliseconds
200
; $_}
get-aduser : The server has returned the following error: invalid enumeration context.
At line:
1
char:
1
+ get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop | ForEac ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : The server has returned the following error: invalid enumeration context.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
After a while of running, we once again get our «The server has returned the following error: invalid enumeration context.» error, but why? The code runs fine without the pipeline, and it runs fine with the pipeline as long as the subsequent cmdlets complete
quickly. We know that the Get-ADUser cmdlet completes in about 30 seconds without the pipeline. Is it the same when we have slower processing further down the pipe?
Let’s do two things to see what is going on. We will use TCPView and Measure-Command, as we did before, to see what is going on from a network perspective and how long our code is running before generating the error.
PS C:>Measure-Command -Expression {get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop | ForEach-Object {Start-Sleep -Milliseconds
200
; $_}}
After 5 minutes of running, we see that we have only received 2.15 Mbytes of data.
After 10 minutes of running, we are only sitting at 4.09 Mbytes of data.
Our slow data rate return continues until we finally error out after 30 minutes, and we also see that we did not receive our expected full data size of around 14.79 Mbytes.
get-aduser : The server has returned the following error: invalid enumeration context.
At line:
1
char:
30
+ Measure-Command -Expression {get-aduser -Filter {-NOT(UserAccountControl -band
2
...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : The server has returned the following error: invalid enumeration context.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Days :
0
Hours :
0
Minutes :
30
Seconds :
49
Milliseconds :
886
Ticks :
18498861406
TotalDays :
0.0214107192199074
TotalHours :
0.513857261277778
TotalMinutes :
30.8314356766667
TotalSeconds :
1849.8861406
TotalMilliseconds :
1849886.1406
So our data is returning a lot slower, and we are erring out before receiving our full dataset. This is indicative of a timeout. Since we know that we are connecting to Active Directory Web Services, a quick web search for «Active Directory Web Services
Timeout 30 minutes» gets us here: https://technet.microsoft.com/en-us/library/dd391908(v=ws.10).aspx
Excerpt from above site:
MaxEnumContextExpiration
Specifies the maximum allowed time period during which the ADWS service processes and retrieves the results of a query request from a client computer.
Changing the
default
value of this parameter is strongly discouraged. Most of the search results are returned within
30
minutes.
Ok, lets put together what we’ve learned.
- Get-ADUser uses paging (256 object per page by default)
- It is up to the client to request new Pages
- When piping out AD Objects, the longer the code down the pipeline takes to process, the slower we retrieve data from Active Directory Web Services
- If that slower processing causes the retrieval time to run over 30 minutes, then the Enumeration Context Expires
Now lets fill in the blanks for the full, end to end process.
- Get-ADUser executes sending the query to Active Directory Web Services
- Active Directory Web Service receives the query, creates an enumeration context for the results, and returns the first page of results containing 256 objects
- Get-ADUser receives those results and sends them down the pipeline, but does not query Active Directory Web Services for the next page until the pipeline has finished processing all 256 objects already received.
- The pipeline processes each object placed in it one at a time down the entire pipeline. So all pipeline processes are completed on the first object before the second object begins it journey down the pipeline. (For 256 objects with 200 millisecond pipeline
processing per item, that’s 51.2 seconds per page. With 14163 object, we are looking at 55.32 pages and 47.21 minutes.) - Once all 256 objects have been processed for the current page, Get-ADUser requests the next page of results from Active Directory Web Services.
- Active Directory Web Services returns the next 256 objects.
- Steps 3 — 6 repeat until all objects are retrieve or the processing time goes longer than 30 minutes. After 30 minutes, Active Directory Web Services expires the enumeration context it created in step 2. Once expired, Active Directory Web Services returns
the error, «invalid enumeration context», when Get-ADUser request the next page because the enumeration context has expired and is no longer valid.
So mystery solved.
Solutions
There are two possible solutions to this issue, the first of which I would not recommend.
- Increase the «MaxEnumContextExpiration» value for Active Directory Web Service. There are many reasons not to take this approach.
- First and foremost, Microsoft recommends again this. «Changing the default value of this parameter is strongly discouraged. Most of the search results are returned within 30 minutes.»
- This change would have to be made on all Domain Controllers that the script would possibly hit.
- The target value to increase to would be a moving target depending on number of objects returned and length of time required to process all pipeline code.
- Increasing this value increases the potential impact of long running processes on your Domain Controllers.
- If you choose this method, it can be done by modifying the «Microsoft.ActiveDirectory.WebServices.exe.config» file in the ADWS directory. By default: «C:WindowsADWS».
- Retrieve your Active Directory objects to a variable first, then send it down the pipeline using the variable. This method is easy to implement in your code without lots of configuration changes in your Active Directory environment. It works because writing
the objects to a variable is very fast so your Get-ADUser and Get-ADComputer cmdlets can quickly write all object to the variable and request the next page until all object are received.
It’s this simple:
Instead of doing this:
get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop | ForEach-Object {Start-Sleep -Milliseconds
200
; $_}
Do this:
$adobjects = get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop
$adobjects | ForEach-Object {Start-Sleep -Milliseconds
200
; $_}
Or if you wanna keep it on a single commandline for the PowerShell console, just separate it with a semicolon:
$adobjects = get-aduser -Filter {-NOT(UserAccountControl -band
2
)} -ErrorAction Stop; $adobjects | ForEach-Object {Start-Sleep -Milliseconds
200
; $_}
My hope is that you will find this useful. Please feel free to leave a comment and let me know how it has helped. Thanks for reading!
The blog post Bill linked suggests the problem is worsened if you query based on an attribute that is not indexed. The operatingSystem (and also the operatingSystemVersion) attribute is not indexed. Assuming you have a large number of computer
objects in your domain, and you frequently query based on OS, it perhaps makes sense to make operatingSystem indexed. This is controlled by the searchFlags attribute of the attribute (of the attribute object in the cn=Schema container). This is a flag
attribute, similar to userAccountControl, where each bit of the integer corresponds to a different setting. In this case, the bit mask for IS_INDEXED is 1. In my domain, the searchFlags attribute of the operatingSystem attribute has no value. If this
is also true in your domain, you could simply assign the value 1 to make operatingSystem indexed.
In ADSI Edit, navigate to the container cn=Schema,cn=Configuration,dc=MyDomain,dc=com, find the attribute with name «Operating-System» (the Common Name is «Operating-System», but the LDAPDisplayName is «operatingSystem»), right click and select «Properties»,
find the searchFlags attribute, click «Edit» and enter the value 1. Then save. I assume it takes awhile for the attribute to be indexed.
My guess is that the Get-ADComputer cmdlet is prone to this problem because it retrieves a default set of properties, whether you need them or not. Some of these properties require code to convert into friendly formats, like objectGUID and SID. You only
add one additional property, but it also requires code to convert into a friendly format. This makes the recordset larger than necessary, and requires more work on the DC. So, another workaround might be to use DirectorySearcher instead of Get-ADComputer.
If this approach is of interest, I have a PowerShell V1 script linked on this page:
http://www.rlmueller.net/PwdLastChanged.htm
which documents the datetime the password was last changed for all users in the domain. This could be modified for all computers with the specified OS’s by replacing the LDAP syntax filter with this:
$Searcher.Filter
= «(&(objectcategory=computer)(|(operatingSystem=Windows 7*)(operatingSystem=Windows XP*)))»
-----
You would add your code to compare pwdLastSet to your critical values and move the appropriate objects. Come to think of it, I also have a PowerShell V1 script that moves old computers (based on pwdLastSet) linked on this page:
http://www.rlmueller.net/MoveOldComputers.htm
In this case the filter includes a clause to only consider enabled computer accounts (testing the flag attribute userAccountControl). You can add the clauses for operatingSystem (use the OR operator «|» to filter on either W7 orXP), and you can remove the
clause with userAccountControl if you also want to consider disabled accounts.
In my experience, these PowerShell V1 scripts are faster than ones using Get-ADComputer in PowerShell V2. This may not be true in PowerShell V3, which supposedly has greatly improved the efficiency of the AD cmdlets. In fact, another workaround for you might
be PowerShell V3.
Richard Mueller — MVP Directory Services
-
Marked as answer by
Sunday, February 3, 2013 2:06 PM
The blog post Bill linked suggests the problem is worsened if you query based on an attribute that is not indexed. The operatingSystem (and also the operatingSystemVersion) attribute is not indexed. Assuming you have a large number of computer
objects in your domain, and you frequently query based on OS, it perhaps makes sense to make operatingSystem indexed. This is controlled by the searchFlags attribute of the attribute (of the attribute object in the cn=Schema container). This is a flag
attribute, similar to userAccountControl, where each bit of the integer corresponds to a different setting. In this case, the bit mask for IS_INDEXED is 1. In my domain, the searchFlags attribute of the operatingSystem attribute has no value. If this
is also true in your domain, you could simply assign the value 1 to make operatingSystem indexed.
In ADSI Edit, navigate to the container cn=Schema,cn=Configuration,dc=MyDomain,dc=com, find the attribute with name «Operating-System» (the Common Name is «Operating-System», but the LDAPDisplayName is «operatingSystem»), right click and select «Properties»,
find the searchFlags attribute, click «Edit» and enter the value 1. Then save. I assume it takes awhile for the attribute to be indexed.
My guess is that the Get-ADComputer cmdlet is prone to this problem because it retrieves a default set of properties, whether you need them or not. Some of these properties require code to convert into friendly formats, like objectGUID and SID. You only
add one additional property, but it also requires code to convert into a friendly format. This makes the recordset larger than necessary, and requires more work on the DC. So, another workaround might be to use DirectorySearcher instead of Get-ADComputer.
If this approach is of interest, I have a PowerShell V1 script linked on this page:
http://www.rlmueller.net/PwdLastChanged.htm
which documents the datetime the password was last changed for all users in the domain. This could be modified for all computers with the specified OS’s by replacing the LDAP syntax filter with this:
$Searcher.Filter
= «(&(objectcategory=computer)(|(operatingSystem=Windows 7*)(operatingSystem=Windows XP*)))»
-----
You would add your code to compare pwdLastSet to your critical values and move the appropriate objects. Come to think of it, I also have a PowerShell V1 script that moves old computers (based on pwdLastSet) linked on this page:
http://www.rlmueller.net/MoveOldComputers.htm
In this case the filter includes a clause to only consider enabled computer accounts (testing the flag attribute userAccountControl). You can add the clauses for operatingSystem (use the OR operator «|» to filter on either W7 orXP), and you can remove the
clause with userAccountControl if you also want to consider disabled accounts.
In my experience, these PowerShell V1 scripts are faster than ones using Get-ADComputer in PowerShell V2. This may not be true in PowerShell V3, which supposedly has greatly improved the efficiency of the AD cmdlets. In fact, another workaround for you might
be PowerShell V3.
Richard Mueller — MVP Directory Services
-
Marked as answer by
Sunday, February 3, 2013 2:06 PM
- Remove From My Forums
-
Вопрос
-
Набросал небольшой скриптец, запускаю на весь домен:
Get-ADComputer -filter * -SearchBase "DC=domain,DC=local" -Properties operatingsystem | ForEach-Object{ if(Test-Connection -ComputerName $_.Name -Count 1 -Quiet) { If($_.Operatingsystem -like "*2008*" -or $_.Operatingsystem -like "*2012*" ) { $params = @{ "Namespace" = "rootcimv2TerminalServices" "Class" = "Win32_TerminalServiceSetting" "ComputerName" = $_.Name} get-wmiobject @params | foreach{ new-object PSObject -property @{ "ComputerName" = $_.ServerName "TerminalServerMode" = $_.TerminalServerMode "LicenseServer" = $_.GetSpecifiedLicenseServerList().SpecifiedLSList } | select-object ComputerName,TerminalServerMode,LicenseServer } } elseif($_.Operatingsystem -like "*2003*") { $params = @{ "Namespace" = "rootcimv2" "Class" = "Win32_TerminalServiceSetting" "ComputerName" = $_.Name} get-wmiobject @params | foreach{ new-object PSObject -property @{ "ComputerName" = $_.ServerName "TerminalServerMode" = $_.TerminalServerMode "LicenseServer" = $_.GetSpecifiedLicenseServerList().SpecifiedLSList } | select-object ComputerName,TerminalServerMode,LicenseServer } } } else {Write-Host $_.Name "Not Ping"} }
Обрабатывает с сотню компов, а потом получаю invalid enumeration context
В get-adcomputer можно поиграть значение resultpagesize поставив например в значение 10, тогда выводит чуть больше, но все равно не достаточно. Как избавиться от этого?
Ответы
-
1) Можно задать более жесткий фильтр:
Get-ADComputer -filter "OperaingSystem -like '*Server*' -and Enabled -eq '$true'" -ResultPageSize 10 -Properties operatingsystem
2) Использовать ADSI:
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $Domain = [ADSI]"LDAP://$D" $Searcher = New-Object System.DirectoryServices.DirectorySearcher $Searcher.PageSize = 200 $Searcher.SearchScope = "subtree" $Searcher.Filter = "(&(objectcategory=computer)(operatingSystem=*Server*))" $Searcher.PropertiesToLoad.Add("operatingSystem") > $Null $Searcher.PropertiesToLoad.Add("name") > $Null $Searcher.SearchRoot = "LDAP://" + $Domain.distinguishedName $Results = $Searcher.FindAll() $Results | Foreach { $OS = $Result.Properties.Item("operatingsystem") $Name = $Result.Properties.Item("name") }
3) Установить атрибут IS_INDEXED = 1 для OperatingSystem —
http://jeffwouters.nl/index.php/2013/09/1760/-
Изменено
9 июня 2015 г. 20:14
-
Помечено в качестве ответа
Дмитрий Трясов
11 июня 2015 г. 5:51
-
Изменено
-
-
Помечено в качестве ответа
Дмитрий Трясов
11 июня 2015 г. 9:34
-
Помечено в качестве ответа
Для получения различной информации об учетных записях компьютера (серверах и рабочих станциях) в домене Active Directory можно использовать PowerShell командлет Get-ADComputer. Это один из наиболее полезных командлетов для выборки и поиска компьютеров по разным критериям в домене AD
Содержание:
- Вывести атрибуты компьютера с помощью Get-ADComputer
- Использование фильтров в Get-ADComputer
- Полезные примеры использования командлета Get-ADComputer
Допустим, ваша задача – найти в Active Directory все неактивные компьютеры, которые не регистрировались в домене более 120 дней и заблокировать учетные записи этих компьютеров.
Прежде чем приступить к работе с командлетом Get-ADComputer, необходимо установить и импортировать модуль Active Directory Module для Windows PowerShell.
Import-Module activedirectory
Совет. В версии PowerShell 3.0 (представлен в Windows Server 2012) и выше этот модуль подключается по умолчанию при установке компонента Remote Server Administration Tools -> Role Administration Tools -> AD DS and AD LDS Tools -> Active Directory модуль для Windows PowerShell. Чтобы использовать командлет Get-ADComputer в клиентских Windows 11 или 10 нужно скачать и установить компонент RSAT для вашей версии ОС и включить модуль AD-PowerShell из панели управления или командой:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
Вывести атрибуты компьютера с помощью Get-ADComputer
Справка о параметрах командлета Get-ADComputer вызывается стандартно с помощью Get-Help:
Get-Help Get-ADComputer
Для получения информации из AD с помощью командлетов модуля AD для Powershell не обязательно иметь права администратора домена, достаточно чтобы учетная запись под которой запускается командлет входила в группу пользователей домена (Authenticated Users / Domain Users).
Чтобы получить информацию о доменной учетной записи конкретного компьютера или сервера, укажите его имя в качестве аргумента параметра —Identity:
Get-ADComputer -Identity SRV-DB01
DistinguishedName : CN=DB01,OU=Servers,OU=MSK,DC=winitpro,DC=ru DNSHostName : DB01.winitpro.ru Enabled : True Name : DB01 ObjectClass : computer ObjectGUID : 1234567c-13f8-4a2c-8b00-b30a32324103 SamAccountName : DB01$ SID : S-1-5-21-3243682314-1360322815-2238451561-4318 UserPrincipalName :
Командлет вернул только базовые свойства объекта Computer из AD . Нас интересует время последней регистрации компьютера в домене AD, но этой информация в выводе команды нет. Выведем все доступные свойства (атрибуты) данного компьютера из Active Directory:
Get-ADComputer -Identity SRV-DB01 -Properties *
Этот список атрибутов компьютера также доступен в графической консоли Active Directory Users and Computers (
dsa.msc
) на вкладке редактора атрибутов.
С помощью Get-Member можно получить список всех свойств класса Computer в AD:
Get-ADComputer -Filter * -Properties * | Get-Member
Как вы видите, время последнего входа данного компьютера в сеть указано в атрибуте компьютера LastLogonDate – 6/2/2022 3:59:30 AM.
Командлет Get-ADComputer позволяет вывести в результатах команды любые из свойств компьютера. Уберем всю лишнюю информацию, оставив в выводе только значения атрибутов Name и LastLogonDate.
Get-ADComputer -identity SRV-DB01 -Properties * | FT Name, LastLogonDate -Autosize
Итак, мы получили данные о последнем времени регистрации в домене для одного компьютера. Теперь нам нужно изменить команду так, чтобы она возвращала информацию о времени последней регистрации в сети для всех компьютеров домена. Для этого заменим параметр –Identity на —Filter:
Get-ADComputer -Filter * -Properties * | FT Name, LastLogonDate -Autosize
Мы получили таблицу, которая содержит только 2 поля: имя компьютера и дата LastLogonData. Вы можете добавить в эту таблицу другие поля объекта Computer из AD. Чтобы вывести данные о компьютерах в определенном контейнере домена (OU), воспользуйтесь параметром SearchBase:
Get-ADComputer -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -Filter * -Properties * | FT Name, LastLogonDate -Autosize
Отсортируем результаты запроса по времени последнего логина в сеть (поле LastLogonDate) с помощью команды Sort:
Get-ADComputer -Filter * -Properties * | Sort LastLogonDate | FT Name, LastLogonDate -Autosize
Итак, мы получили список компьютеров домена и время их последнего входа в сеть Active Directory. Теперь мы хотим заблокировать учетные записи компьютеров, которые не использовались более 120 дней.
С помощью Get-Date получим в переменной значение текущей даты и вычтем из текущей даты 120 дней:
$date_with_offset= (Get-Date).AddDays(-120)
Полученную переменную с датой можно использовать в качестве фильтра запроса Get-ADComputer по полю LastLogonDate
Get-ADComputer -Properties LastLogonDate -Filter {LastLogonDate -lt $date_with_offset } | Sort LastLogonDate | FT Name, LastLogonDate -Autosize
Таким образом, мы получили список неактивных компьютеров, которые не регистрировались в домене более 120 дней. С помощью командлета Set-ADComputer или Disable-ADAccount вы можете отключить эти учетные записи.
Совет. В первый раз лучше протестировать результаты команды с помощью переключателя –WhatIf, благодаря которому команда не вносит никаких изменений, показывая, что произойдет при ее выполнении.
Get-ADComputer -Properties LastLogonDate -Filter {LastLogonData -lt $date_with_offset } | Set-ADComputer -Enabled $false -whatif
Теперь можно заблокировать все найденные учетные записи компьютеров:
Get-ADComputer -Properties LastLogonDate -Filter {LastLogonData -lt $date_with_offset} | Set-ADComputer -Enabled $false
Совет. Список заблокированных, отключенных и неактивных компьютеров и пользователей домена можно получить также с помощью отдельного командлета Search-ADAccount.
Использование фильтров в Get-ADComputer
С помощью аргумента -Filter командлета Get-ADComputer вы можете выбрать несколько компьютеров Active Directory по определенным критериями. Здесь можно использовать подстановочные знаки (wildcards) и логические операторы сравнения. В качестве фильтров можно использовать только базовые атрибуты компьютера.
Если вам нужно использовать фильтры по расширенными атрибутам компьютеров, их можно задавать через where-object. Несколько примеров есть в следующем разделе статьи.
Получить общее количество активных (незаблокированных) компьютеров в Active Directory:
(Get-ADComputer -Filter {enabled -eq "true"}).count
Вы можете использовать множественные фильтры для поиска компьютеров по нескольким параметрам сразу. Для этого используются логические операторы сравнения PowerShell (-and, -eq , -ne , -gt , -ge , -lt , -le , -like , -notlike , -and , -or , и т.д.).
Посчитать количество серверов с Windows Server в домене:
(Get-ADComputer -Filter {enabled -eq "true" -and OperatingSystem -Like '*Windows Server*' }).count
Получить список компьютеров в определенном OU, имена которых начинаются с BuhPC:
Get-ADComputer -Filter {Name -like "BuhPC*"} -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -Properties IPv4Address | Format-table Name,DNSHostName,IPv4Address | ft -Wrap –Auto
При поиске по OU вы можете использовать дополнительный параметр -SearchScope 1, который означает, что нужно искать только в корневом разделе. Параметр -SearchScope 2 означает рекурсивный поиск компьютеров во всех вложенных OU.
Выбрать все рабочие станции с ОС Windows 10:
Get-ADComputer -Filter {OperatingSystem -like '*Windows 10*'}
Получить список серверов в домене с версией ОС, IP адресом и установленным Service Pack:
Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -Properties Name,Operatingsystem, OperatingSystemVersion, OperatingSystemServicePack,IPv4Address | Sort-Object -Property Operatingsystem | Select-Object -Property Name,Operatingsystem, OperatingSystemVersion, OperatingSystemServicePack, IPv4Address| ft -Wrap –Auto
На выходе получили такую красивую таблицу со списком Windows Server в AD.
Полезные примеры использования командлета Get-ADComputer
Ниже представлены еще несколько полезных примеров команд с использованием командлета Get-ADComputer, которые можно использовать для выборки и поиска компьютеров домена по определенными критериям.
Атрибут -LDAPFilter позволяет использовать в качестве параметра командлета Get-ADComputer различные LDAP запросы, например:
Get-ADComputer -LDAPFilter "(name=*db*)"|ft
Выбрать заблокированные компьютеры в определенном OU:
Get-ADComputer -filter * -SearchBase ‘OU=Computers, dc=winitpro,dc=loc’ | Where-Object {$_.enabled -eq $False}
Чтобы удалить все аккаунты компьютеров в домене, не авторизовавшиеся в домене более 6 месяцев, можете воспользоваться командой:
get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate -lt (get-date).addmonths(-6) } | Remove-ADComputer
Вывести время последней смены пароля компьютера в Active Directory. По умолчанию пароль должен меняться компьютером автоматически раз в 30 дней, если пароль компьютера не совпадает с паролем в AD, доверительные отношения компьютера с доменом будут нарушены:
Get-ADComputer –Identity pc123456 -Properties PasswordLastSet
Результат выполнения команды Get-ADComputer можно выгрузить в текстовый файл:
Get-ADComputer -Filter { OperatingSystem -Like '*Windows Server 2019*' } -Properties OperatingSystem | Select DNSHostName, OperatingSystem | Format-Table -AutoSize C:Scriptserver_system.txt
Также вы можете получить выборку компьютеров и экспортировать его в CSV файл:
Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemServicePack | Export-CSV All-Windows.csv -NoTypeInformation -Encoding UTF8
Или получить HTML файл отчета со списком компьютеров и нужных атрибутов компьютера:
Get-ADComputer -Filter {OperatingSystem -Like '*Windows Server 2012*' } -Properties * | Select-Object Name,OperatingSystem | ConvertTo-Html | Out-File C:psad_computer.html
Можно удалено получить различную информацию с компьютеров AD через WMI (или CIM). Например, вывести серийные номера всех серверов в домене:
Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' | Select-Object Name | Foreach-Object {Get-CimInstance Win32_Bios -ComputerName $_.Name -ErrorAction SilentlyContinue | Select-Object PSComputerName,SerialNumber}
Чтобы выполнить определенной действие со всеми компьютерами из полученного списка нужно использовать цикл Foreach. В этом примере мы хотим получить список серверов в домене с моделью и производителем:
$Computers = Get-ADComputer -Filter {OperatingSystem -Like '*Windows Server*'}
Foreach ($Computer in $Computers)
{
$Hostname = $Computer.Name
$ComputerInfo = (Get-WmiObject -Computername $Hostname Win32_ComputerSystem)
$Manufacturer = $Computer.Manufacturer
$Model = $Computer.Model
Write-Host "Name: $Hostname"
Write-Host "Manufacturer: $Manufacturer"
Write-Host "Model: $Model"
Write-Host " "
$Content = "$Hostname;$Manufacturer;$Model"
Add-Content -Value $Content -Path "C:PSServersInfo.txt"
}
Либо можно использовать более короткий синтаксис цикла. Допустим нам нужно выполнить определенную команду на всех компьютерах в определенном OU. В этом примере мы с помощью Invoke-Command выполним на всех серверах команду обновления настроек групповых политик:
get-adcomputer -SearchBase "OU=Servers,DC=winitpro,DC=loc" -Filter * | %{ Invoke-Command -Computer $_.Name -ScriptBlock {gpupdate /force} }
С помощью Get-ADComputer и логон скриптов PowerShell вы можете контролировать различные параметры компьютера или хранить различную полезную информацию в атрибутах компьютера в AD (можно например добавить имя пользователя в описание компьютера).
Я, например, контролирую состояние агента SCCM на компьютерах пользователей. При загрузке каждого компьютера на нем отрабатывает логон скрипт, который с помощью Set-ADComputer сохраняет состояние службы ccmexec в свободный атрибут компьютера — extensionAttribute10.
Затем с помощью следующей команды я могу найти компьютеры, на которых отсутствует или не запушена служба CCMExec:
get-adcomputer -filter {extensionAttribute10 -ne "SCCM Agent:Running"} -SearchBase “OU=Computers,OU=MSK,DC=winitpro,DC=ru” -properties dNSHostName,extensionAttribute10,LastLogonDate |select-object dNSHostName,extensionAttribute10,LastLogonDate
Для получения информации об учетных записях пользователей AD используется другой командлет — Get-ADUser .
#powershell
#powershell
Вопрос:
Я пытаюсь получить всех подрядчиков и сотрудников из нашего AD с включенным true для фильтра. Сам AD очень большой и содержит много данных, что может привести к ограничению времени ожидания при запуске сценария powershell. Я получаю эту ошибку, когда я помещаю ее в переменную, и если я выполняю прямой экспорт, я получаю ограничение по времени ожидания.
Есть ли какой-либо способ собрать все данные подрядчика и сотрудника с включенными сотрудниками с big AD без возникновения этой проблемы? Я получаю вывод, но не уверен, что вывод осуществим, поскольку я получаю сообщение об ошибке.
Спасибо
Param(
[Parameter(Mandatory = $true,ValueFromPipeline = $false,HelpMessage = "Specify a output file name and path.")]
[string]
$OutputFileNamePath = $null
)
$Storage = @()
Write-Host "**********************************************************" -ForegroundColor Green
Write-Host "* On Process *" -ForegroundColor Green
Write-Host "**********************************************************" -ForegroundColor Green
$filter = @("CONTRACTOR", "EMPLOYEE")
$Storage = Get-ADUser -Filter * -Properties EmployeeNumber,Name,SamAccountName,employeeType,PasswordLastSet,LastLogonDate | Where {($_.Enabled -eq $True) -and $filter -contains $_.employeeType} | Select EmployeeNumber,Name,SamAccountName,employeeType,PasswordLastSet,LastLogonDate
$Storage | Export-Csv -Path $OutputFileNamePath".csv" -Force
Write-Host "**********************************************************" -ForegroundColor Green
Write-Host "* Done *" -ForegroundColor Green
Write-Host "**********************************************************" -ForegroundColor Green
Ответ №1:
Эта статья TechNet дает нам подсказку о том, почему может возникнуть эта ошибка, в основном:
- Get-ADUser использует подкачку (по умолчанию 256 объектов на страницу)
- Запрашивать новые страницы должен клиент
- При конвейерной передаче объектов AD чем дольше обрабатывается код в конвейере, тем медленнее мы извлекаем данные из веб-служб Active Directory
- Если из-за более медленной обработки время поиска превышает 30 минут, то контекст перечисления истекает
Скорее всего, ваш запрос выполняется в течение 30 минут, что приводит к этому исключению. Решение этой проблемы заключается в создании более эффективного запроса, чтобы он завершался до этого времени или, что не рекомендуется MS:
Увеличьте значение «MaxEnumContextExpiration» для веб-службы Active Directory. Есть много причин не использовать этот подход.
Вы можете использовать LDAPFilter
для повышения производительности вашего запроса, Where-Object
в этом случае использование не требуется:
$properties = 'EmployeeNumber', 'employeeType', 'PasswordLastSet', 'LastLogonDate'
$filter = '(amp;(!userAccountControl:1.2.840.113556.1.4.803:=2)(|(employeeType=CONTRACTOR)(employeeType=EMPLOYEE)))'
Get-ADUser -LDAPFilter $filter -Properties $properties
Чтобы преобразовать фильтр LDAP во что-то читаемое:
amp;
— Логический И Операторный|
— Логический оператор OR(!userAccountControl:1.2.840.113556.1.4.803:=2)
— Включен пользовательский объект(|(employeeType=CONTRACTOR)(employeeType=EMPLOYEE))
—employeeType
является «Подрядчиком» ИЛИ «сотрудником»(amp;(...)(|(...)(...)))
— Все предложения должны быть выполнены. Мы можем прочитать это как:
(Пользователь включен) И (пользовательemployeeType
— «Подрядчик» ИЛИ «Сотрудник»)
Для дальнейшего использования Active Directory: фильтры синтаксиса LDAP
Комментарии:
1. Спасибо! Это работает для меня!
2. @Den10102020 рад помочь 😉
Ответ №2:
Я изменил ваш скрипт, но я просто собрал всех пользователей в $Users
массив, а затем запустил ForEach
цикл для каждого отдельного пользователя. Внутри есть If
функция, которая проверяет, включен ли пользователь и что EmployeeType является -like
CONTRACTOR или EMPLOYEE . Если они есть, он добавляет их в $Storage
массив, а затем экспортирует его после завершения цикла.
У меня это сработало, но дайте мне знать, если у вас возникнут какие-либо вопросы:
Param(
[Parameter(Mandatory = $true,ValueFromPipeline = $false,HelpMessage = "Specify a output file name and path.")]
[string]
$OutputFileNamePath = $null
)
$Storage = @()
Write-Host "----------------------------------------------------------" -ForegroundColor Green
Write-Host "- On Process -" -ForegroundColor Green
Write-Host "----------------------------------------------------------" -ForegroundColor Green
$Users = Get-ADUser -Filter * -Properties EmployeeNumber,Name,SamAccountName,employeeType,PasswordLastSet,LastLogonDate
Foreach($user in $users){
If(($User.Enabled -eq $True) -and (($User.EmployeeType -like "*CONTRACTOR*") -or (($User.EmployeeType -like "*EMPLOYEE*")))){
$Storage = $User
}
}
$Storage | Export-Csv -Path $OutputFileNamePath".csv" -NoTypeInformation -Force
Write-Host "----------------------------------------------------------" -ForegroundColor Green
Write-Host "- Done -" -ForegroundColor Green
Write-Host "----------------------------------------------------------" -ForegroundColor Green
Комментарии:
1. Привет, Джош! Спасибо за помощь, но у меня такая же проблема на моей стороне. Решение LDAP работает для меня
2. @Den10102020 Нет проблем! Я видел комментарий выше, рад, что он смог определить, в чем заключалась ошибка, и помочь вам ее устранить.
3. Он отличное соединение! Большинство моих проблем с PowerShell были решены г-ном Скварзоном