-
Notifications
You must be signed in to change notification settings - Fork 72
/
LAPSToolkit.ps1
3061 lines (2249 loc) · 91.8 KB
/
LAPSToolkit.ps1
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
<#
LAPSToolkit
Uses many functions from PowerView
URL: https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1
Author: Will Schroeder (@harmj0y)
Credits:
Will Schroeder (@harmj0y),
Sean Metcalf (@pyrotek3),
Matt Graeber (@mattifestation),
Karl Fosaaen (@kfosaaen)
#>
########################################################
#
# Functions from PowerView
# Author: Will Schroeder (@harmj0y)
#
########################################################
filter Export-PowerViewCSV {
<#
.SYNOPSIS
This helper exports an -InputObject to a .csv in a thread-safe manner
using a mutex. This is so the various multi-threaded functions in
PowerView has a thread-safe way to export output to the same file.
Based partially on Dmitry Sotnikov's Export-CSV code
at http://poshcode.org/1590
.LINK
http://poshcode.org/1590
http://dmitrysotnikov.wordpress.com/2010/01/19/Export-Csv-append/
#>
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[System.Management.Automation.PSObject[]]
$InputObject,
[Parameter(Mandatory=$True, Position=0)]
[String]
[ValidateNotNullOrEmpty()]
$OutFile
)
$ObjectCSV = $InputObject | ConvertTo-Csv -NoTypeInformation
# mutex so threaded code doesn't stomp on the output file
$Mutex = New-Object System.Threading.Mutex $False,'CSVMutex';
$Null = $Mutex.WaitOne()
if (Test-Path -Path $OutFile) {
# hack to skip the first line of output if the file already exists
$ObjectCSV | ForEach-Object { $Start=$True }{ if ($Start) {$Start=$False} else {$_} } | Out-File -Encoding 'ASCII' -Append -FilePath $OutFile
}
else {
$ObjectCSV | Out-File -Encoding 'ASCII' -Append -FilePath $OutFile
}
$Mutex.ReleaseMutex()
}
filter Convert-SidToName {
<#
.SYNOPSIS
Converts a security identifier (SID) to a group/user name.
.PARAMETER SID
The SID to convert.
.EXAMPLE
PS C:\> Convert-SidToName S-1-5-21-2620891829-2411261497-1773853088-1105
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
[ValidatePattern('^S-1-.*')]
$SID
)
try {
$SID2 = $SID.trim('*')
# try to resolve any built-in SIDs first
# from https://support.microsoft.com/en-us/kb/243330
Switch ($SID2)
{
'S-1-0' { 'Null Authority' }
'S-1-0-0' { 'Nobody' }
'S-1-1' { 'World Authority' }
'S-1-1-0' { 'Everyone' }
'S-1-2' { 'Local Authority' }
'S-1-2-0' { 'Local' }
'S-1-2-1' { 'Console Logon ' }
'S-1-3' { 'Creator Authority' }
'S-1-3-0' { 'Creator Owner' }
'S-1-3-1' { 'Creator Group' }
'S-1-3-2' { 'Creator Owner Server' }
'S-1-3-3' { 'Creator Group Server' }
'S-1-3-4' { 'Owner Rights' }
'S-1-4' { 'Non-unique Authority' }
'S-1-5' { 'NT Authority' }
'S-1-5-1' { 'Dialup' }
'S-1-5-2' { 'Network' }
'S-1-5-3' { 'Batch' }
'S-1-5-4' { 'Interactive' }
'S-1-5-6' { 'Service' }
'S-1-5-7' { 'Anonymous' }
'S-1-5-8' { 'Proxy' }
'S-1-5-9' { 'Enterprise Domain Controllers' }
'S-1-5-10' { 'Principal Self' }
'S-1-5-11' { 'Authenticated Users' }
'S-1-5-12' { 'Restricted Code' }
'S-1-5-13' { 'Terminal Server Users' }
'S-1-5-14' { 'Remote Interactive Logon' }
'S-1-5-15' { 'This Organization ' }
'S-1-5-17' { 'This Organization ' }
'S-1-5-18' { 'Local System' }
'S-1-5-19' { 'NT Authority' }
'S-1-5-20' { 'NT Authority' }
'S-1-5-80-0' { 'All Services ' }
'S-1-5-32-544' { 'BUILTIN\Administrators' }
'S-1-5-32-545' { 'BUILTIN\Users' }
'S-1-5-32-546' { 'BUILTIN\Guests' }
'S-1-5-32-547' { 'BUILTIN\Power Users' }
'S-1-5-32-548' { 'BUILTIN\Account Operators' }
'S-1-5-32-549' { 'BUILTIN\Server Operators' }
'S-1-5-32-550' { 'BUILTIN\Print Operators' }
'S-1-5-32-551' { 'BUILTIN\Backup Operators' }
'S-1-5-32-552' { 'BUILTIN\Replicators' }
'S-1-5-32-554' { 'BUILTIN\Pre-Windows 2000 Compatible Access' }
'S-1-5-32-555' { 'BUILTIN\Remote Desktop Users' }
'S-1-5-32-556' { 'BUILTIN\Network Configuration Operators' }
'S-1-5-32-557' { 'BUILTIN\Incoming Forest Trust Builders' }
'S-1-5-32-558' { 'BUILTIN\Performance Monitor Users' }
'S-1-5-32-559' { 'BUILTIN\Performance Log Users' }
'S-1-5-32-560' { 'BUILTIN\Windows Authorization Access Group' }
'S-1-5-32-561' { 'BUILTIN\Terminal Server License Servers' }
'S-1-5-32-562' { 'BUILTIN\Distributed COM Users' }
'S-1-5-32-569' { 'BUILTIN\Cryptographic Operators' }
'S-1-5-32-573' { 'BUILTIN\Event Log Readers' }
'S-1-5-32-574' { 'BUILTIN\Certificate Service DCOM Access' }
'S-1-5-32-575' { 'BUILTIN\RDS Remote Access Servers' }
'S-1-5-32-576' { 'BUILTIN\RDS Endpoint Servers' }
'S-1-5-32-577' { 'BUILTIN\RDS Management Servers' }
'S-1-5-32-578' { 'BUILTIN\Hyper-V Administrators' }
'S-1-5-32-579' { 'BUILTIN\Access Control Assistance Operators' }
'S-1-5-32-580' { 'BUILTIN\Access Control Assistance Operators' }
Default {
$Obj = (New-Object System.Security.Principal.SecurityIdentifier($SID2))
$Obj.Translate( [System.Security.Principal.NTAccount]).Value
}
}
}
catch {
Write-Debug "Invalid SID: $SID"
$SID
}
}
filter Convert-ADName {
<#
.SYNOPSIS
Converts user/group names from NT4 (DOMAIN\user) or domainSimple ([email protected])
to canonical format (domain.com/Users/user) or NT4.
Based on Bill Stewart's code from this article:
http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
.PARAMETER ObjectName
The user/group name to convert.
.PARAMETER InputType
The InputType of the user/group name ("NT4","Simple","Canonical").
.PARAMETER OutputType
The OutputType of the user/group name ("NT4","Simple","Canonical").
.EXAMPLE
PS C:\> Convert-ADName -ObjectName "dev\dfm"
Returns "dev.testlab.local/Users/Dave"
.EXAMPLE
PS C:\> Convert-SidToName "S-..." | Convert-ADName
Returns the canonical name for the resolved SID.
.LINK
http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
$ObjectName,
[String]
[ValidateSet("NT4","Simple","Canonical")]
$InputType,
[String]
[ValidateSet("NT4","Simple","Canonical")]
$OutputType
)
$NameTypes = @{
"Canonical" = 2
"NT4" = 3
"Simple" = 5
}
if(!$PSBoundParameters['InputType']) {
if( ($ObjectName.split('/')).Count -eq 2 ) {
$ObjectName = $ObjectName.replace('/', '\')
}
if($ObjectName -match "^[A-Za-z]+\\[A-Za-z ]+$") {
$InputType = 'NT4'
}
elseif($ObjectName -match "^[A-Za-z ]+@[A-Za-z\.]+") {
$InputType = 'Simple'
}
elseif($ObjectName -match "^[A-Za-z\.]+/[A-Za-z]+/[A-Za-z/ ]+") {
$InputType = 'Canonical'
}
else {
Write-Warning "Can not identify InType for $ObjectName"
return $ObjectName
}
}
elseif($InputType -eq 'NT4') {
$ObjectName = $ObjectName.replace('/', '\')
}
if(!$PSBoundParameters['OutputType']) {
$OutputType = Switch($InputType) {
'NT4' {'Canonical'}
'Simple' {'NT4'}
'Canonical' {'NT4'}
}
}
# try to extract the domain from the given format
$Domain = Switch($InputType) {
'NT4' { $ObjectName.split("\")[0] }
'Simple' { $ObjectName.split("@")[1] }
'Canonical' { $ObjectName.split("/")[0] }
}
# Accessor functions to simplify calls to NameTranslate
function Invoke-Method([__ComObject] $Object, [String] $Method, $Parameters) {
$Output = $Object.GetType().InvokeMember($Method, "InvokeMethod", $Null, $Object, $Parameters)
if ( $Output ) { $Output }
}
function Set-Property([__ComObject] $Object, [String] $Property, $Parameters) {
[Void] $Object.GetType().InvokeMember($Property, "SetProperty", $Null, $Object, $Parameters)
}
$Translate = New-Object -ComObject NameTranslate
try {
Invoke-Method $Translate "Init" (1, $Domain)
}
catch [System.Management.Automation.MethodInvocationException] {
Write-Debug "Error with translate init in Convert-ADName: $_"
}
Set-Property $Translate "ChaseReferral" (0x60)
try {
Invoke-Method $Translate "Set" ($NameTypes[$InputType], $ObjectName)
(Invoke-Method $Translate "Get" ($NameTypes[$OutputType]))
}
catch [System.Management.Automation.MethodInvocationException] {
Write-Debug "Error with translate Set/Get in Convert-ADName: $_"
}
}
function ConvertFrom-UACValue {
<#
.SYNOPSIS
Converts a UAC int value to human readable form.
.PARAMETER Value
The int UAC value to convert.
.PARAMETER ShowAll
Show all UAC values, with a + indicating the value is currently set.
.EXAMPLE
PS C:\> ConvertFrom-UACValue -Value 66176
Convert the UAC value 66176 to human readable format.
.EXAMPLE
PS C:\> Get-NetUser jason | select useraccountcontrol | ConvertFrom-UACValue
Convert the UAC value for 'jason' to human readable format.
.EXAMPLE
PS C:\> Get-NetUser jason | select useraccountcontrol | ConvertFrom-UACValue -ShowAll
Convert the UAC value for 'jason' to human readable format, showing all
possible UAC values.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
$Value,
[Switch]
$ShowAll
)
begin {
# values from https://support.microsoft.com/en-us/kb/305144
$UACValues = New-Object System.Collections.Specialized.OrderedDictionary
$UACValues.Add("SCRIPT", 1)
$UACValues.Add("ACCOUNTDISABLE", 2)
$UACValues.Add("HOMEDIR_REQUIRED", 8)
$UACValues.Add("LOCKOUT", 16)
$UACValues.Add("PASSWD_NOTREQD", 32)
$UACValues.Add("PASSWD_CANT_CHANGE", 64)
$UACValues.Add("ENCRYPTED_TEXT_PWD_ALLOWED", 128)
$UACValues.Add("TEMP_DUPLICATE_ACCOUNT", 256)
$UACValues.Add("NORMAL_ACCOUNT", 512)
$UACValues.Add("INTERDOMAIN_TRUST_ACCOUNT", 2048)
$UACValues.Add("WORKSTATION_TRUST_ACCOUNT", 4096)
$UACValues.Add("SERVER_TRUST_ACCOUNT", 8192)
$UACValues.Add("DONT_EXPIRE_PASSWORD", 65536)
$UACValues.Add("MNS_LOGON_ACCOUNT", 131072)
$UACValues.Add("SMARTCARD_REQUIRED", 262144)
$UACValues.Add("TRUSTED_FOR_DELEGATION", 524288)
$UACValues.Add("NOT_DELEGATED", 1048576)
$UACValues.Add("USE_DES_KEY_ONLY", 2097152)
$UACValues.Add("DONT_REQ_PREAUTH", 4194304)
$UACValues.Add("PASSWORD_EXPIRED", 8388608)
$UACValues.Add("TRUSTED_TO_AUTH_FOR_DELEGATION", 16777216)
$UACValues.Add("PARTIAL_SECRETS_ACCOUNT", 67108864)
}
process {
$ResultUACValues = New-Object System.Collections.Specialized.OrderedDictionary
if($Value -is [Int]) {
$IntValue = $Value
}
elseif ($Value -is [PSCustomObject]) {
if($Value.useraccountcontrol) {
$IntValue = $Value.useraccountcontrol
}
}
else {
Write-Warning "Invalid object input for -Value : $Value"
return $Null
}
if($ShowAll) {
foreach ($UACValue in $UACValues.GetEnumerator()) {
if( ($IntValue -band $UACValue.Value) -eq $UACValue.Value) {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)+")
}
else {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)")
}
}
}
else {
foreach ($UACValue in $UACValues.GetEnumerator()) {
if( ($IntValue -band $UACValue.Value) -eq $UACValue.Value) {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)")
}
}
}
$ResultUACValues
}
}
filter Get-Proxy {
<#
.SYNOPSIS
Enumerates the proxy server and WPAD conents for the current user.
.PARAMETER ComputerName
The computername to enumerate proxy settings on, defaults to local host.
.EXAMPLE
PS C:\> Get-Proxy
Returns the current proxy settings.
#>
param(
[Parameter(ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
[String]
$ComputerName = $ENV:COMPUTERNAME
)
try {
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser', $ComputerName)
$RegKey = $Reg.OpenSubkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
$ProxyServer = $RegKey.GetValue('ProxyServer')
$AutoConfigURL = $RegKey.GetValue('AutoConfigURL')
$Wpad = ""
if($AutoConfigURL -and ($AutoConfigURL -ne "")) {
try {
$Wpad = (New-Object Net.Webclient).DownloadString($AutoConfigURL)
}
catch {
Write-Warning "Error connecting to AutoConfigURL : $AutoConfigURL"
}
}
if($ProxyServer -or $AutoConfigUrl) {
$Properties = @{
'ProxyServer' = $ProxyServer
'AutoConfigURL' = $AutoConfigURL
'Wpad' = $Wpad
}
New-Object -TypeName PSObject -Property $Properties
}
else {
Write-Warning "No proxy settings found for $ComputerName"
}
}
catch {
Write-Warning "Error enumerating proxy settings for $ComputerName : $_"
}
}
function Get-PathAcl {
<#
.SYNOPSIS
Enumerates the ACL for a given file path.
.PARAMETER Path
The local/remote path to enumerate the ACLs for.
.PARAMETER Recurse
If any ACL results are groups, recurse and retrieve user membership.
.EXAMPLE
PS C:\> Get-PathAcl "\\SERVER\Share\"
Returns ACLs for the given UNC share.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
$Path,
[Switch]
$Recurse
)
begin {
function Convert-FileRight {
# From http://stackoverflow.com/questions/28029872/retrieving-security-descriptor-and-getting-number-for-filesystemrights
[CmdletBinding()]
param(
[Int]
$FSR
)
$AccessMask = @{
[uint32]'0x80000000' = 'GenericRead'
[uint32]'0x40000000' = 'GenericWrite'
[uint32]'0x20000000' = 'GenericExecute'
[uint32]'0x10000000' = 'GenericAll'
[uint32]'0x02000000' = 'MaximumAllowed'
[uint32]'0x01000000' = 'AccessSystemSecurity'
[uint32]'0x00100000' = 'Synchronize'
[uint32]'0x00080000' = 'WriteOwner'
[uint32]'0x00040000' = 'WriteDAC'
[uint32]'0x00020000' = 'ReadControl'
[uint32]'0x00010000' = 'Delete'
[uint32]'0x00000100' = 'WriteAttributes'
[uint32]'0x00000080' = 'ReadAttributes'
[uint32]'0x00000040' = 'DeleteChild'
[uint32]'0x00000020' = 'Execute/Traverse'
[uint32]'0x00000010' = 'WriteExtendedAttributes'
[uint32]'0x00000008' = 'ReadExtendedAttributes'
[uint32]'0x00000004' = 'AppendData/AddSubdirectory'
[uint32]'0x00000002' = 'WriteData/AddFile'
[uint32]'0x00000001' = 'ReadData/ListDirectory'
}
$SimplePermissions = @{
[uint32]'0x1f01ff' = 'FullControl'
[uint32]'0x0301bf' = 'Modify'
[uint32]'0x0200a9' = 'ReadAndExecute'
[uint32]'0x02019f' = 'ReadAndWrite'
[uint32]'0x020089' = 'Read'
[uint32]'0x000116' = 'Write'
}
$Permissions = @()
# get simple permission
$Permissions += $SimplePermissions.Keys | % {
if (($FSR -band $_) -eq $_) {
$SimplePermissions[$_]
$FSR = $FSR -band (-not $_)
}
}
# get remaining extended permissions
$Permissions += $AccessMask.Keys |
? { $FSR -band $_ } |
% { $AccessMask[$_] }
($Permissions | ?{$_}) -join ","
}
}
process {
try {
$ACL = Get-Acl -Path $Path
$ACL.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | ForEach-Object {
$Names = @()
if ($_.IdentityReference -match '^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+') {
$Object = Get-ADObject -SID $_.IdentityReference
$Names = @()
$SIDs = @($Object.objectsid)
if ($Recurse -and (@('268435456','268435457','536870912','536870913') -contains $Object.samAccountType)) {
$SIDs += Get-NetGroupMember -SID $Object.objectsid | Select-Object -ExpandProperty MemberSid
}
$SIDs | ForEach-Object {
$Names += ,@($_, (Convert-SidToName $_))
}
}
else {
$Names += ,@($_.IdentityReference.Value, (Convert-SidToName $_.IdentityReference.Value))
}
ForEach($Name in $Names) {
$Out = New-Object PSObject
$Out | Add-Member Noteproperty 'Path' $Path
$Out | Add-Member Noteproperty 'FileSystemRights' (Convert-FileRight -FSR $_.FileSystemRights.value__)
$Out | Add-Member Noteproperty 'IdentityReference' $Name[1]
$Out | Add-Member Noteproperty 'IdentitySID' $Name[0]
$Out | Add-Member Noteproperty 'AccessControlType' $_.AccessControlType
$Out
}
}
}
catch {
Write-Warning $_
}
}
}
filter Get-NameField {
<#
.SYNOPSIS
Helper that attempts to extract appropriate field names from
passed computer objects.
.PARAMETER Object
The passed object to extract name fields from.
.PARAMETER DnsHostName
A DnsHostName to extract through ValueFromPipelineByPropertyName.
.PARAMETER Name
A Name to extract through ValueFromPipelineByPropertyName.
.EXAMPLE
PS C:\> Get-NetComputer -FullData | Get-NameField
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Object]
$Object,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[String]
$DnsHostName,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[String]
$Name
)
if($PSBoundParameters['DnsHostName']) {
$DnsHostName
}
elseif($PSBoundParameters['Name']) {
$Name
}
elseif($Object) {
if ( [bool]($Object.PSobject.Properties.name -match "dnshostname") ) {
# objects from Get-NetComputer
$Object.dnshostname
}
elseif ( [bool]($Object.PSobject.Properties.name -match "name") ) {
# objects from Get-NetDomainController
$Object.name
}
else {
# strings and catch alls
$Object
}
}
else {
return $Null
}
}
function Convert-LDAPProperty {
<#
.SYNOPSIS
Helper that converts specific LDAP property result fields.
Used by several of the Get-Net* function.
.PARAMETER Properties
Properties object to extract out LDAP fields for display.
#>
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
$Properties
)
$ObjectProperties = @{}
$Properties.PropertyNames | ForEach-Object {
if (($_ -eq "objectsid") -or ($_ -eq "sidhistory")) {
# convert the SID to a string
$ObjectProperties[$_] = (New-Object System.Security.Principal.SecurityIdentifier($Properties[$_][0],0)).Value
}
elseif($_ -eq "objectguid") {
# convert the GUID to a string
$ObjectProperties[$_] = (New-Object Guid (,$Properties[$_][0])).Guid
}
elseif( ($_ -eq "lastlogon") -or ($_ -eq "lastlogontimestamp") -or ($_ -eq "pwdlastset") -or ($_ -eq "lastlogoff") -or ($_ -eq "badPasswordTime") ) {
# convert timestamps
if ($Properties[$_][0] -is [System.MarshalByRefObject]) {
# if we have a System.__ComObject
$Temp = $Properties[$_][0]
[Int32]$High = $Temp.GetType().InvokeMember("HighPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
[Int32]$Low = $Temp.GetType().InvokeMember("LowPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
$ObjectProperties[$_] = ([datetime]::FromFileTime([Int64]("0x{0:x8}{1:x8}" -f $High, $Low)))
}
else {
$ObjectProperties[$_] = ([datetime]::FromFileTime(($Properties[$_][0])))
}
}
elseif($Properties[$_][0] -is [System.MarshalByRefObject]) {
# try to convert misc com objects
$Prop = $Properties[$_]
try {
$Temp = $Prop[$_][0]
Write-Verbose $_
[Int32]$High = $Temp.GetType().InvokeMember("HighPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
[Int32]$Low = $Temp.GetType().InvokeMember("LowPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
$ObjectProperties[$_] = [Int64]("0x{0:x8}{1:x8}" -f $High, $Low)
}
catch {
$ObjectProperties[$_] = $Prop[$_]
}
}
elseif($Properties[$_].count -eq 1) {
$ObjectProperties[$_] = $Properties[$_][0]
}
else {
$ObjectProperties[$_] = $Properties[$_]
}
}
New-Object -TypeName PSObject -Property $ObjectProperties
}
filter Get-DomainSearcher {
<#
.SYNOPSIS
Helper used by various functions that takes an ADSpath and
domain specifier and builds the correct ADSI searcher object.
.PARAMETER Domain
The domain to use for the query, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER ADSpath
The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
.PARAMETER ADSprefix
Prefix to set for the searcher (like "CN=Sites,CN=Configuration")
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-DomainSearcher -Domain testlab.local
.EXAMPLE
PS C:\> Get-DomainSearcher -Domain testlab.local -DomainController SECONDARY.dev.testlab.local
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Domain,
[String]
$DomainController,
[String]
$ADSpath,
[String]
$ADSprefix,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
if(!$Credential) {
if(!$Domain){
$Domain = (Get-NetDomain).name
}
elseif(!$DomainController) {
try {
# if there's no -DomainController specified, try to pull the primary DC
# to reflect queries through
$DomainController = ((Get-NetDomain).PdcRoleOwner).Name
}
catch {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
}
}
elseif (!$DomainController) {
try {
$DomainController = ((Get-NetDomain -Credential $Credential).PdcRoleOwner).Name
}
catch {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
if(!$DomainController) {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
}
$SearchString = "LDAP://"
if($DomainController) {
$SearchString += $DomainController
if($Domain){
$SearchString += "/"
}
}
if($ADSprefix) {
$SearchString += $ADSprefix + ","
}
if($ADSpath) {
if($ADSpath -like "GC://*") {
# if we're searching the global catalog
$DN = $AdsPath
$SearchString = ""
}
else {
if($ADSpath -like "LDAP://*") {
if($ADSpath -match "LDAP://.+/.+") {
$SearchString = ""
}
else {
$ADSpath = $ADSpath.Substring(7)
}
}
$DN = $ADSpath
}
}
else {
if($Domain -and ($Domain.Trim() -ne "")) {
$DN = "DC=$($Domain.Replace('.', ',DC='))"
}
}
$SearchString += $DN
Write-Verbose "Get-DomainSearcher search string: $SearchString"
if($Credential) {
Write-Verbose "Using alternate credentials for LDAP connection"
$DomainObject = New-Object DirectoryServices.DirectoryEntry($SearchString, $Credential.UserName, $Credential.GetNetworkCredential().Password)
$Searcher = New-Object System.DirectoryServices.DirectorySearcher($DomainObject)
}
else {
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
}
$Searcher.PageSize = $PageSize
$Searcher
}
filter Get-NetDomain {
<#
.SYNOPSIS
Returns a given domain object.
.PARAMETER Domain
The domain name to query for, defaults to the current domain.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetDomain -Domain testlab.local
.EXAMPLE
PS C:\> "testlab.local" | Get-NetDomain
.LINK
http://social.technet.microsoft.com/Forums/scriptcenter/en-US/0c5b3f83-e528-4d49-92a4-dee31f4b481c/finding-the-dn-of-the-the-domain-without-admodule-in-powershell?forum=ITCG
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Domain,
[Management.Automation.PSCredential]
$Credential
)
if($Credential) {
Write-Verbose "Using alternate credentials for Get-NetDomain"
if(!$Domain) {
# if no domain is supplied, extract the logon domain from the PSCredential passed
$Domain = $Credential.GetNetworkCredential().Domain
Write-Verbose "Extracted domain '$Domain' from -Credential"
}
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain, $Credential.UserName, $Credential.GetNetworkCredential().Password)
try {
[System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
}
catch {
Write-Warning "The specified domain does '$Domain' not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid."
$Null
}
}
elseif($Domain) {
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain)
try {
[System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
}
catch {
Write-Warning "The specified domain '$Domain' does not exist, could not be contacted, or there isn't an existing trust."
$Null
}
}
else {
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
}
}
filter Get-NetForest {
<#
.SYNOPSIS
Returns a given forest object.
.PARAMETER Forest
The forest name to query for, defaults to the current domain.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetForest -Forest external.domain
.EXAMPLE
PS C:\> "external.domain" | Get-NetForest
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Forest,
[Management.Automation.PSCredential]
$Credential
)
if($Credential) {
Write-Verbose "Using alternate credentials for Get-NetForest"
if(!$Forest) {
# if no domain is supplied, extract the logon domain from the PSCredential passed
$Forest = $Credential.GetNetworkCredential().Domain
Write-Verbose "Extracted domain '$Forest' from -Credential"
}
$ForestContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', $Forest, $Credential.UserName, $Credential.GetNetworkCredential().Password)