-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathADEnumerator.psm1
1045 lines (805 loc) · 64 KB
/
ADEnumerator.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 2
<#
Install steps:
1) Since this is a module, you may need to disable the execution
policy. From an elevated prompt, execute the following:
Set-ExecutionPolicy Unrestricted
2) From a regular PowerShell prompt, you can now import the module.
Import-Module ADEnumerator.psm1
ADEnumerator.psm1 contains a lot of functions which will each accept
an existing LDAP session parameteter (LDAPSession) or a new one (DCHostName).
Call the New-LDAPSession function and set it to a variable to create an existing
LDAP session that will be passed to the other functions.
Notes:
This is only ever intended to be executed on your attacker system.
It will run on any system though, but you will always have to provide creds.
You will need a valid domain controller for this to work.
How do you get a list of domain controllers without a domain system?
Two ways:
ipconfig -> will get you a DNS suffix
nltest /dclist:{domain} #will give you an error, but will also list one DC
nslookup
set type=any
{domain} #will list name servers...generally those are DCs
Use Cases:
1. You harvest a domain credential from a printer, responder, etc. But don't have access
to a domain system. You can use the credential to perform additional enumeration on the domain.
2. Find out what you can do with the credential you harvested. What group membership, maybe a system with similiar
naming convetion of the username which indicates the user may have local admin on the system.
3. You are provided credentials to start an internal assessment, but not a domain system.
4. You just want to do domain enumeration quickly
Function Overview:
New-LDAPSession - Creates an LDAP Session
Invoke-SearchAD - Searches Active Directory for string
Get-AllADUsers - Will get all user accounts from Active Directory
Get-GroupMembership - Will get user accounts who are members of specified group
Get-AllGroups - Gets a list of all groups
Get-DomainControllers - Gets a list of domain controllers
Get-Computers - Gets a list of computers or computer versions
Get-UserMembership - Will get details about specified user
.SYNOPSIS
Active Directory enumeration from non-domain system.
Author: Evan Peña
Credit: Matt Graeber for code review and code improvements
Required Dependencies: Domain Credential
Optional Dependencies: Expand-Data
.DESCRIPTION
ADEnumerator.psm1 allows red teamers to query LDAP with a standard user account
from a system not joined to a domain. It's common that during a red team assessment
you will harvest credentials from printers, files, etc. But sometimes you don't know
what these credentials do.
Instead of throwing the one set of credentials you got at all systems to see where you
are local admin, you can tailor your attack to specific systems. ADEnumerator.ps1 allows
you to find out information about the account you compromised. It will also perform all
the Active Directory enumeration you can do from a domain system using the creds you obtained.
.EXAMPLE
C:\PS> import-module ADEnumerator.psm1
C:\PS> $Domain = New-LDAPSession -DCHostName ServerDC.contoso.local
Description
-----------
Will establish an LDAP session with domain controller ServerDC.contoso.local
and save it into variable $domain
.EXAMPLE
C:\PS> Get-AllADUsers -LDAPSession $domain
Description
-----------
Will return all users in the domain using
the existing LDAP session from New-LDAPSession
#>
function New-LDAPSession
{
<#
.SYNOPSIS
Creates an LDAP Session
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Will establish an LDAP session with a valid domain account.
It will return an object that can be used for other functions
in this module.
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.EXAMPLE
$Domain = New-LDAPSession -DCHostName ServerDC.contoso.local
.EXAMPLE
powerpick $domain=New-LDAPSession -DCHostName DC1 -UserName user1 -Password StrongPassWord;Get-Computers -LDAPSession $domain -Version 10 | Out-File C:\temp\win10.txt
#>
[CmdletBinding(DefaultParameterSetName='DomainInfoSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Parameter(Mandatory = $True, ParameterSetName="inline")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="inline")]
[String]
$Username,
[Parameter(Mandatory = $True, ParameterSetName="inline")]
[String]
$Password
)
if ($Credential) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
elseif ($Username) {
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
#Ensure creds are good and can establish connection
trap { $script:err = $_ ; continue } &{ $domain.Bind($true); $script:err = $null }
if ($err.Exception.ErrorCode -ne -2147352570)
{
Write-Host -Fore Red $err.Exception.Message
break
}
else
{
Write-Host -Fore Green "Connection established."
}
#Write-Host Logon failure: unknown user name or bad password.
return $domain
}
function Invoke-SearchAD
{
<#
.SYNOPSIS
Searches Active Directory for string
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Will search Active Directory for a string like something.
If you know a persons first name, but not sure of their last name,
you can use this search to find all users with a first name specified
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.PARAMETER SearchString
Specifies the search string you are looking for
.PARAMETER Groups
Switch that will specify to search all groups in active directory for specified string
.PARAMETER Users
Switch that will specify to search all users and machines in active directory for specified string
.EXAMPLE
Invoke-SearchAD -DCHostName ServerDC.contoso.local -SearchString *evan* -Users
.EXAMPLE
Invoke-SearchAD -LDAPSession $domain -SearchString *admin* -Groups
.EXAMPLE
Invoke-SearchAD -LDAPSession $domain -SearchString *pena* -Users
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoGroups")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoUsers")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoGroups")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoUsers")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionGroups")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionUsers")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoGroups")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoUsers")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionGroups")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionUsers")]
[ValidateNotNullOrEmpty()]
[String]
$SearchString,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoGroups")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionGroups")]
[ValidateNotNullOrEmpty()]
[switch]
$Groups,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoUsers")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionUsers")]
[ValidateNotNullOrEmpty()]
[switch]
$Users
)
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
if ($PSboundparameters["Groups"]) {
$type = "ObjectCategory=group"
}
else {
$type = "objectClass=user"
}
$dsLookFor = new-object DirectoryServices.DirectorySearcher($domain)
$dsLookFor.filter = "(&($type)(sAMAccountName=$SearchString))"
$dsLookFor.CacheResults = $true
$dsLookFor.SearchScope = "Subtree"
$dsLookFor.PageSize = 1000
$lstUsr = $dsLookFor.findall()
foreach ($usrTmp in $lstUsr)
{
$usrTmp.Properties["samaccountname"][0]
}
}
#This function will get all active AD user accounts to include the samaccountname and full name
function Get-AllADUsers
{
<#
.SYNOPSIS
Will get all user accounts from Active Directory
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Will get all user accounts from Active Directory
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.EXAMPLE
Get-AllADUsers -DCHostName ServerDC.contoso.local
.EXAMPLE
Get-AllADUsers -LDAPSession $domain
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession
)
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
$dsLookFor = New-Object System.DirectoryServices.DirectorySearcher
#$dsLookFor.filter ="(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
$dsLookFor.filter ="(sAMAccountType=805306368)" #per Carlos' Derby talk slide 404
$dsLookFor.SearchRoot = $domain
$dsLookFor.PropertiesToLoad.Add("samaccountname")
$dsLookFor.PageSize = 1000
$dsLookFor.Filter = $strFilter
$dsLookFor.SearchScope = "Subtree"
$colProplist = "name"
foreach ($i in $colPropList){$dsLookFor.PropertiesToLoad.Add($i)}
$colResults = $dsLookFor.FindAll()
foreach ($objResult in $colResults) {
if ($objResult.Properties['samaccountname'])
{
if ($objResult.Properties['samaccountname'] -ne "")
{
if (!($objResult.Properties['samaccountname'][0].EndsWith("$")))
{
New-Object PSObject -Property @{
Name = $objResult.Properties['name'][0]
Account = $objResult.Properties['samaccountname'][0]
}
}
}
}
}
}
#######get distinguishedname for groups to add to the group of interest
Function Invoke-SearchGroups
{
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[String]
$GroupName
)
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($LDAPSession)
$dsLookFor.filter = $Filter = "(&(ObjectCategory=group))"
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "Subtree"
$lstUsr = $dsLookFor.Findall()
foreach ($usrTmp in $lstUsr)
{
#$usrTmp.Properties['distinguishedname']
$grpName = $usrTmp.Properties['name']
if ($GroupName -eq $grpName)
{
$dg = $usrTmp.Properties['distinguishedname']
}
}
return $dg
}
Function Get-GroupMembership
{
<#
.SYNOPSIS
Will get user accounts who are members of specified group
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Will get user accounts who are members of specified group
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.PARAMETER GroupName
Specifies group name you want members of. Accepts single group name, array of group names, or a list piped to it
.EXAMPLE
Get-GroupMembership -DCHostName ServerDC.contoso.local -GroupName finance
.EXAMPLE
gc groupNameList.txt | Get-GroupMembership -DCHostName ServerDC.contoso.local
.EXAMPLE
Get-GroupMembership -LDAPSession $domain -GroupName "domain admins"
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet", ValueFromPipeLine=$True)]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet", ValueFromPipeLine=$True)]
[ValidateNotNullOrEmpty()]
[String[]]
$GroupName
)
Process {
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
foreach ($group in $GroupName) {
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($domain)
$DNGrp = Invoke-SearchGroups -GroupName $group -LDAPSession $domain
$dsLookFor.filter = "(&(objectCategory=user)(memberOf=$DNGrp))"
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "subtree";
$n = $dsLookFor.PropertiesToLoad.Add("cn");
$n = $dsLookFor.PropertiesToLoad.Add("distinguishedName");
$n = $dsLookFor.PropertiesToLoad.Add("samaccountname");
$lstUsr = $dsLookFor.findall()
"All Users for: $group"
foreach ($usrTmp in $lstUsr)
{
if ($usrTmp.Properties['samaccountname'] -and ($usrTmp.Properties['samaccountname'][0].Length -ne 0))
{
$usrTmp.Properties["samaccountname"][0]
}
}
"`n"
}
}
}
function Get-AllGroups
{
<#
.SYNOPSIS
Gets a list of all groups
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Gets a list of all groups
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.EXAMPLE
Get-AllGroups -DCHostName ServerDC.contoso.local
.EXAMPLE
Get-AllGroups -LDAPSession $domain
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession
)
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($domain)
$dsLookFor.filter = $Filter = "(&(ObjectCategory=group))"
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "Subtree"
$n = $dsLookFor.PropertiesToLoad.Add("cn");
$n = $dsLookFor.PropertiesToLoad.Add("description");
$n = $dsLookFor.PropertiesToLoad.Add("samaccountname");
$lstUsr = $dsLookFor.Findall()
foreach ($usrTmp in $lstUsr)
{
if ($usrTmp.Properties['samaccountname'] -and ($usrTmp.Properties['samaccountname'][0].Length -ne 0))
{
$SamAccountName = $usrTmp.Properties['samaccountname'][0]
$Description = $null
if ($usrTmp.Properties['description'] -and ($usrTmp.Properties['description'][0].Length -ne 0)) {
$Description = $usrTmp.Properties['description'][0]
}
New-Object PSObject -Property @{
SAMAccountName = $SamAccountName
Description = $Description
}
}
}
}
Function Get-DomainControllers
{
<#
.SYNOPSIS
Gets a list of domain controllers
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Gets a list of domain controllers
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.EXAMPLE
Get-DomainControllers -DCHostName ServerDC.contoso.local
.EXAMPLE
Get-DomainControllers -LDAPSession $domain
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession
)
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($domain)
$dsLookFor.filter = "(&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))" #Taken from Carlos' Derby talk slide 404
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "subtree";
$n = $dsLookFor.PropertiesToLoad.Add("sAMAccountName");
$lstUsr = $dsLookFor.findall()
foreach ($usrTmp in $lstUsr)
{
$usrTmp.Properties["samaccountname"][0].replace("$","")
}
}
#LDAP filtered referenced fro here: http://blogs.msdn.com/b/muaddib/archive/2011/10/24/active-directory-ldap-searches.aspx
Function Get-Computers
{
<#
.SYNOPSIS
Gets a list of computers or computer versions
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
This function will get a list of computers from Active Directory. This function
can be flexible. If you want only SQL servers, Windows Servers, specific versions, etc.
The function will default to all computers if a parameter is not specified
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.PARAMETER Sql
Will return a list of SQL systems from Active Directory
.PARAMETER Servers
Will return a list of all Windows servers from Active Directory
.PARAMETER Windows
Will return a list of all Windows systems from Active Directory.
Includes Workstations and Servers
.PARAMETER Version
Specifies the operating system version you want.
Following values accepted: 7, 2008, XP, 2000, 2003, Vista, 2012, 8, 10
.EXAMPLE
Get-Computers -DCHostName ServerDC.contoso.local -Sql
.EXAMPLE
Get-Computers -LDAPSession $domain -Servers | Out-File allServers.txt
.EXAMPLE
Get-Computers -LDAPSession $domain -Version 2000 | Out-File all2000Systems.txt
.EXAMPLE
Get-Computers -LDAPSession $domain -Windows
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetSql")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetServers")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetWindows")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetVersion")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetSql")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetServers")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetWindows")]
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetVersion")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetSql")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetServers")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetWindows")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetVersion")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetSql")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetSql")]
[Switch]
$Sql,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetServers")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetServers")]
[Switch]
$Servers,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetWindows")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetWindows")]
[Switch]
$Windows,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSetVersion")]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSetVersion")]
[ValidateSet('7', '2008', 'XP', '2000', '2003', 'Vista', '2012', '8', '10')]
[String]
$Version
)
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
$AllFilter = '(objectCategory=computer)'
$SqlFilter = '(&(objectCategory=computer)(servicePrincipalName=MSSQLSvc*)(operatingSystem=Windows Server*))'
$ServerFilter = '(&((objectCategory=computer))(operatingSystem=Windows Server*))'
$WindowsFilter = '(&(objectCategory=computer)(operatingSystem=Windows*))'
$ServerVersions = @('2008', '2012', '2003')
switch ($PSCmdlet.ParameterSetName) {
'LDAPSessionSet' { $Filter = '(objectCategory=computer)' }
'DomainInfoSet' { $Filter = '(objectCategory=computer)' }
'LDAPSessionSetSql' { $Filter = $SqlFilter }
'DomainInfoSetSql' { $Filter = $SqlFilter }
'LDAPSessionSetServers' { $Filter = $ServerFilter }
'DomainInfoSetServers' { $Filter = $ServerFilter }
'LDAPSessionSetWindows' { $Filter = $WindowsFilter }
'DomainInfoSetWindows' { $Filter = $WindowsFilter }
'DomainInfoSetVersion' {
if ($ServerVersions -contains $Version) {
$Filter = "(&(objectCategory=computer)(operatingSystem=Windows Server $version*))"
} else {
$Filter = "(&(objectCategory=computer)(operatingSystem=Windows $version*))"
}
}
'LDAPSessionSetVersion' {
if ($ServerVersions -contains $Version) {
$Filter = "(&(objectCategory=computer)(operatingSystem=Windows Server $version*))"
} else {
$Filter = "(&(objectCategory=computer)(operatingSystem=Windows $version*))"
}
}
}
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($domain)
$dsLookFor.filter = $Filter
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "subtree"
$n = $dsLookFor.PropertiesToLoad.Add("samaccountname")
$lstUsr = $dsLookFor.findall()
# Are you sure you'll still only interested in just the samaccountname and description?
foreach ($usrTmp in $lstUsr)
{
if ($usrTmp.Properties['samaccountname'] -and ($usrTmp.Properties['samaccountname'][0].Length -ne 0))
{
$SamAccountName = $usrTmp.Properties['samaccountname'][0].replace("$", "")
$Description = $null
if ($usrTmp.Properties['description'] -and ($usrTmp.Properties['description'][0].Length -ne 0)) {
$Description = $usrTmp.Properties['description'][0]
}
New-Object PSObject -Property @{
SAMAccountName = $SamAccountName
Description = $Description
}
}
}
}
Function Get-UserMembership
{
<#
.SYNOPSIS
Will get details about specified user
Author: Evan Peña
License: GPLv3
Required Dependencies: Domain Account
Optional Dependencies: None
.DESCRIPTION
Will get details about specified user. Details will include group membership,
account lockout, etc.
.PARAMETER DCHostName
Specifies the domain controller that will be used to esablish an LDAP connection.
.PARAMETER LDAPSession
Uses an existing LDAP session obtained from New-LDAPSession
.PARAMETER UserName
Specifies user name you want details about. Accepts single username, array of usernames, or a list piped to it
.EXAMPLE
Get-UserMembership -DCHostName ServerDC.contoso.local -UserName evan.pena
.EXAMPLE
Get-UserMembership -LDAPSession $domain -UserName evan.pena | Format-Table -Wrap -Proper Name,Value
.EXAMPLE
Get-UserMembership -LDAPSession $domain -UserName evan.pena | Format-List
Description
-----------
If you want to expand table to include all contents
.EXAMPLE
gc UserNameList.txt | Get-UserMembership -LDAPSession $domain
Description
-----------
Will take contenst of username list and get user information from all users in the list
#>
[CmdletBinding(DefaultParameterSetName='LDAPSessionSet')]
Param
(
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[ValidateNotNullOrEmpty()]
[String]
$DCHostName,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet")]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet")]
[ValidateNotNullOrEmpty()]
[DirectoryServices.DirectoryEntry]
$LDAPSession,
[Parameter(Mandatory = $True, ParameterSetName="DomainInfoSet", ValueFromPipeLine=$True)]
[Parameter(Mandatory = $True, ParameterSetName="LDAPSessionSet", ValueFromPipeLine=$True)]
[ValidateNotNullOrEmpty()]
[String[]]
$UserName
)
Process {
if ($PSboundparameters["DCHostName"]) {
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://$DCHostName",$Credential.UserName, $Credential.GetNetworkCredential().Password)
}
else {
$domain = $LDAPSession
}
$dsLookFor = new-object System.DirectoryServices.DirectorySearcher($domain)
$dsLookFor.ClientTimeout = "00:00:05"
$dsLookFor.ServerTimeLimit = "00:00:05"
$allUserData = New-Object HashTable
foreach ($user in $UserName) {
$lstUsr = ""
$usrTmp = ""
$dsLookFor.filter = "(&(objectClass=person)(samaccountname=$user))"
$dsLookFor.PageSize = 1000;
$dsLookFor.SearchScope = "subtree";
$lstUsr = $dsLookFor.findall()
if ($lstUsr -ne "") {
foreach ($usrTmp in $lstUsr)
{
$allUserData.Clear()
$Groups = Get-UserGroups -GroupList $usrTmp.Properties['memberof']
$Groups = $Groups -join ","
$allUserData.Add("memberof", $Groups)
$properties = $usrTmp.Properties.GetEnumerator() | select name
foreach ($i in $properties) {
if ($i.name -eq "samaccountname") {
$allUserData.Add("Account", $usrTmp.Properties['samaccountname'][0])
}
elseif ($i.name -eq "name") {
$allUserData.Add("Name", $usrTmp.Properties['name'][0])
}
elseif ($i.name -eq "samaccountname") {
$allUserData.Add("Account", $usrTmp.Properties['samaccountname'][0])
}
elseif ($i.name -eq "lockouttime") {
$lockOutTime = ConvertTo-Date -TimeStamp $usrTmp.Properties['lockouttime'][0]
$allUserData.Add("LockoutTime", $lockOutTime)
}
elseif ($i.name -eq "accountexpires") {
$accountExpires = ConvertTo-Date -TimeStamp $usrTmp.Properties['accountexpires'][0]
$allUserData.Add("AccountExpires", $accountExpires)
}
elseif ($i.name -eq "pwdlastset") {
$pwdlastset = ConvertTo-Date -TimeStamp $usrTmp.Properties['pwdlastset'][0]
$allUserData.Add("PwdLastSet", $pwdlastset)
}
elseif ($i.name -eq "whenchanged") {
$allUserData.Add("WhenChanged", $usrTmp.Properties['whenchanged'][0])
}
elseif ($i.name -eq "scriptpath") {
$allUserData.Add("ScriptPath", $usrTmp.Properties['scriptpath'][0])
}
elseif ($i.name -eq "lastlogon") {
$LastLogon = ConvertTo-Date -TimeStamp $usrTmp.Properties['lastlogon'][0]
$allUserData.Add("LastLogon", $LastLogon)
}