-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathActiveDirectoryManagement.psm1
More file actions
1299 lines (1071 loc) · 46.1 KB
/
ActiveDirectoryManagement.psm1
File metadata and controls
1299 lines (1071 loc) · 46.1 KB
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
# ActiveDirectoryManagement Module
# Provides functions for managing Active Directory operations
# Supports Windows 10/11 and PowerShell 5.1+
# Import required modules
Import-Module Common
Import-Module ActiveDirectory
# Module compatibility requirements
$script:ModuleRequirements = @{
MinimumOSVersion = "10.0.17763" # Windows 10 1809/Server 2019
ServerOnly = $true # AD operations typically require Server OS
RequiredModules = @('ActiveDirectory')
RequiredFeatures = @('RSAT-AD-PowerShell')
}
# Check module compatibility on import
$compatibility = Test-ModuleCompatibility -ModuleName "ActiveDirectoryManagement" -Requirements $script:ModuleRequirements
if (-not $compatibility.IsCompatible) {
Write-Warning "ActiveDirectoryManagement module may not function correctly on this system. See logs for details."
}
function Test-ADFunctionCompatibility {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$FunctionName,
[Parameter(Mandatory=$false)]
[hashtable]$AdditionalRequirements = @{}
)
try {
# Merge module requirements with function-specific requirements
$requirements = $script:ModuleRequirements.Clone()
foreach ($key in $AdditionalRequirements.Keys) {
$requirements[$key] = $AdditionalRequirements[$key]
}
$compatibility = Test-ModuleCompatibility -ModuleName "ActiveDirectoryManagement.$FunctionName" -Requirements $requirements
return $compatibility.IsCompatible
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to check function compatibility: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADUserAccountInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[string[]]$Properties = @(
'Name',
'SamAccountName',
'DisplayName',
'Enabled',
'LastLogonDate',
'PasswordLastSet',
'Description',
'Department',
'Title',
'Manager',
'MemberOf'
),
[Parameter(Mandatory=$false)]
[string]$Filter,
[Parameter(Mandatory=$false)]
[string]$SearchBase,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADUserAccountInfo")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving AD user account information" -Level Info
$params = @{
Properties = $Properties
ErrorAction = 'Stop'
}
if ($Identity) {
$params['Identity'] = $Identity
}
elseif ($Filter) {
$params['Filter'] = $Filter
}
else {
$params['Filter'] = "ObjectClass -eq 'user'"
}
if ($SearchBase) {
$params['SearchBase'] = $SearchBase
}
$users = Get-ADUser @params
$results = $users | ForEach-Object {
[PSCustomObject]@{
Name = $_.Name
SamAccountName = $_.SamAccountName
DisplayName = $_.DisplayName
Enabled = $_.Enabled
LastLogonDate = $_.LastLogonDate
PasswordLastSet = if ($_.PasswordLastSet) { [DateTime]::FromFileTime($_.PasswordLastSet) } else { $null }
Description = $_.Description
Department = $_.Department
Title = $_.Title
Manager = $_.Manager
MemberOf = ($_.MemberOf | ForEach-Object { (Get-ADGroup $_).Name }) -join ';'
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved account information for $($results.Count) users" -Level Info
return $results | Sort-Object -Property Name
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve user account information: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADInactiveUsers {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[int]$Days = 90,
[Parameter(Mandatory=$false)]
[string]$SearchBase,
[Parameter(Mandatory=$false)]
[switch]$IncludeDisabled,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADInactiveUsers")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving inactive users (inactive for $Days days)" -Level Info
$cutoffDate = (Get-Date).AddDays(-$Days)
$filter = "LastLogonDate -lt '$cutoffDate'"
if (-not $IncludeDisabled) {
$filter += " -and Enabled -eq `$true"
}
$params = @{
Filter = $filter
Properties = @(
'Name',
'SamAccountName',
'Enabled',
'LastLogonDate',
'PasswordLastSet',
'Description',
'Department',
'Title'
)
ErrorAction = 'Stop'
}
if ($SearchBase) {
$params['SearchBase'] = $SearchBase
}
$users = Get-ADUser @params
$results = $users | ForEach-Object {
$lastLogon = if ($_.LastLogonDate) { $_.LastLogonDate } else { "Never" }
$daysInactive = if ($lastLogon -ne "Never") { [math]::Round((Get-Date - $lastLogon).TotalDays) } else { $null }
[PSCustomObject]@{
Name = $_.Name
SamAccountName = $_.SamAccountName
Enabled = $_.Enabled
LastLogonDate = $lastLogon
DaysInactive = $daysInactive
PasswordLastSet = if ($_.PasswordLastSet) { [DateTime]::FromFileTime($_.PasswordLastSet) } else { $null }
Description = $_.Description
Department = $_.Department
Title = $_.Title
Status = switch ($true) {
($daysInactive -gt $Days * 2) { 'Long Term Inactive' }
($daysInactive -gt $Days) { 'Inactive' }
default { 'Active' }
}
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Found $($results.Count) inactive users" -Level Info
return $results | Sort-Object -Property DaysInactive -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve inactive users: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADUserLoginStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[string[]]$ComputerName,
[Parameter(Mandatory=$false)]
[switch]$Detailed,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADUserLoginStatus")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving user login status" -Level Info
$params = @{
Properties = @(
'Name',
'SamAccountName',
'Enabled',
'LastLogonDate',
'LastLogon',
'LogonCount',
'Description'
)
ErrorAction = 'Stop'
}
if ($Identity) {
$params['Identity'] = $Identity
}
else {
$params['Filter'] = "ObjectClass -eq 'user'"
}
$users = Get-ADUser @params
$results = @()
foreach ($user in $users) {
$loginInfo = @{
Name = $user.Name
SamAccountName = $user.SamAccountName
Enabled = $user.Enabled
LastLogonDate = $user.LastLogonDate
LastLogon = if ($user.LastLogon) { [DateTime]::FromFileTime($user.LastLogon) } else { $null }
LogonCount = $user.LogonCount
Description = $user.Description
Status = if ($user.Enabled) { 'Enabled' } else { 'Disabled' }
CurrentLogin = $false
LoginComputers = @()
}
if ($Detailed -and $ComputerName) {
foreach ($computer in $ComputerName) {
try {
$sessions = Get-CimInstance -ClassName Win32_LogonSession -ComputerName $computer -ErrorAction Stop
$userSessions = $sessions | Where-Object { $_.LogonType -in (2, 10) } | ForEach-Object {
Get-CimInstance -ClassName Win32_LoggedOnUser -ComputerName $computer |
Where-Object { $_.Antecedent -like "*$($user.SamAccountName)*" }
}
if ($userSessions) {
$loginInfo.CurrentLogin = $true
$loginInfo.LoginComputers += $computer
}
} catch {
Write-LogMessage -Message "Failed to check login status on $computer : $_" -Level Warning
}
}
}
$results += [PSCustomObject]$loginInfo
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved login status for $($results.Count) users" -Level Info
return $results | Sort-Object -Property LastLogonDate -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve user login status: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADLockedOutUsers {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[int]$Days = 7,
[Parameter(Mandatory=$false)]
[switch]$IncludeHistory,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADLockedOutUsers")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving locked out users" -Level Info
$cutoffDate = (Get-Date).AddDays(-$Days)
$lockedUsers = Get-ADUser -Filter "LockedOut -eq `$true" -Properties @(
'Name',
'SamAccountName',
'Enabled',
'LastLogonDate',
'LockoutTime',
'Description',
'Department',
'Title'
) -ErrorAction Stop
$results = @()
foreach ($user in $lockedUsers) {
$lockoutTime = if ($user.LockoutTime) { [DateTime]::FromFileTime($user.LockoutTime) } else { $null }
$lockoutDuration = if ($lockoutTime) { [math]::Round((Get-Date - $lockoutTime).TotalHours, 2) } else { $null }
$userInfo = @{
Name = $user.Name
SamAccountName = $user.SamAccountName
Enabled = $user.Enabled
LastLogonDate = $user.LastLogonDate
LockoutTime = $lockoutTime
LockoutDuration = $lockoutDuration
Description = $user.Description
Department = $user.Department
Title = $user.Title
Status = if ($lockoutTime -gt $cutoffDate) { 'Recently Locked' } else { 'Locked' }
}
if ($IncludeHistory) {
try {
$dc = Get-ADDomainController -Discover -Service "PrimaryDC" -ErrorAction Stop
$events = Get-WinEvent -ComputerName $dc.HostName -FilterHashtable @{
LogName = 'Security'
ID = 4740
StartTime = $cutoffDate
} -ErrorAction Stop | Where-Object {
$_.Properties[0].Value -eq $user.SamAccountName
}
$userInfo.LockoutHistory = $events | ForEach-Object {
[PSCustomObject]@{
Time = $_.TimeCreated
Computer = $_.Properties[1].Value
Reason = $_.Properties[2].Value
}
}
} catch {
Write-LogMessage -Message "Failed to retrieve lockout history: $_" -Level Warning
$userInfo.LockoutHistory = @()
}
}
$results += [PSCustomObject]$userInfo
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Found $($results.Count) locked out users" -Level Info
return $results | Sort-Object -Property LockoutTime -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve locked out users: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADPasswordStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[int]$ExpiringInDays = 0,
[Parameter(Mandatory=$false)]
[string]$SearchBase,
[Parameter(Mandatory=$false)]
[switch]$IncludeDisabled,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADPasswordStatus")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving AD password status" -Level Info
$params = @{
Properties = @(
'Name',
'SamAccountName',
'Enabled',
'PasswordLastSet',
'PasswordExpired',
'PasswordNeverExpires',
'LastLogonDate',
'Description'
)
ErrorAction = 'Stop'
}
if ($Identity) {
$params['Identity'] = $Identity
}
else {
$filter = "Enabled -eq `$true"
if ($IncludeDisabled) {
$filter = "ObjectClass -eq 'user'"
}
if ($ExpiringInDays -gt 0) {
$expiryDate = (Get-Date).AddDays($ExpiringInDays)
$filter += " -and (PasswordLastSet -lt '$expiryDate')"
}
$params['Filter'] = $filter
}
if ($SearchBase) {
$params['SearchBase'] = $SearchBase
}
$users = Get-ADUser @params
$results = $users | ForEach-Object {
$user = $_
$passwordLastSet = if ($user.PasswordLastSet) { [DateTime]::FromFileTime($user.PasswordLastSet) } else { $null }
$daysUntilExpiry = if ($passwordLastSet) {
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
if ($maxPasswordAge -and -not $user.PasswordNeverExpires) {
$expiryDate = $passwordLastSet.AddDays($maxPasswordAge.TotalDays)
[math]::Round(($expiryDate - (Get-Date)).TotalDays)
} else { $null }
} else { $null }
[PSCustomObject]@{
Name = $user.Name
SamAccountName = $user.SamAccountName
Enabled = $user.Enabled
PasswordLastSet = $passwordLastSet
DaysUntilExpiry = $daysUntilExpiry
PasswordExpired = $user.PasswordExpired
PasswordNeverExpires = $user.PasswordNeverExpires
LastLogonDate = $user.LastLogonDate
Description = $user.Description
Status = switch ($true) {
$user.PasswordExpired { 'Expired' }
$user.PasswordNeverExpires { 'Never Expires' }
($daysUntilExpiry -le 0) { 'Expired' }
($daysUntilExpiry -le 7) { 'Expiring Soon' }
default { 'Valid' }
}
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved password status for $($results.Count) users" -Level Info
return $results | Sort-Object -Property PasswordLastSet -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve password status: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADGroupMembers {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$GroupName,
[Parameter(Mandatory=$false)]
[string[]]$Properties = @(
'Name',
'SamAccountName',
'DisplayName',
'Enabled',
'LastLogonDate',
'Description',
'Department',
'Title'
),
[Parameter(Mandatory=$false)]
[switch]$Recursive,
[Parameter(Mandatory=$false)]
[switch]$IncludeNestedGroups,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADGroupMembers")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving members of group '$GroupName'" -Level Info
$group = Get-ADGroup -Identity $GroupName -ErrorAction Stop
$members = @()
if ($Recursive) {
$members = Get-ADGroupMember -Identity $GroupName -Recursive -ErrorAction Stop
} else {
$members = Get-ADGroupMember -Identity $GroupName -ErrorAction Stop
}
$results = @()
foreach ($member in $members) {
if ($member.objectClass -eq 'user') {
$user = Get-ADUser -Identity $member.SamAccountName -Properties $Properties -ErrorAction Stop
$results += [PSCustomObject]@{
Name = $user.Name
SamAccountName = $user.SamAccountName
DisplayName = $user.DisplayName
Enabled = $user.Enabled
LastLogonDate = $user.LastLogonDate
Description = $user.Description
Department = $user.Department
Title = $user.Title
ObjectClass = 'User'
MemberOf = $GroupName
}
}
elseif ($IncludeNestedGroups -and $member.objectClass -eq 'group') {
$nestedGroup = Get-ADGroup -Identity $member.SamAccountName -Properties Description -ErrorAction Stop
$results += [PSCustomObject]@{
Name = $nestedGroup.Name
SamAccountName = $nestedGroup.SamAccountName
Description = $nestedGroup.Description
ObjectClass = 'Group'
MemberOf = $GroupName
}
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved $($results.Count) members from group '$GroupName'" -Level Info
return $results | Sort-Object -Property ObjectClass, Name
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve group members: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADComputersInOU {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$SearchBase,
[Parameter(Mandatory=$false)]
[string]$Filter,
[Parameter(Mandatory=$false)]
[string[]]$Properties = @(
'Name',
'DNSHostName',
'OperatingSystem',
'OperatingSystemVersion',
'LastLogonDate',
'Description',
'Location',
'ManagedBy',
'Created',
'Modified'
),
[Parameter(Mandatory=$false)]
[switch]$IncludeDisabled,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADComputersInOU")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving computers in OU" -Level Info
$params = @{
Filter = "ObjectClass -eq 'computer'"
Properties = $Properties
ErrorAction = 'Stop'
}
if ($SearchBase) {
$params['SearchBase'] = $SearchBase
}
if ($Filter) {
$params['Filter'] = "($($params['Filter'])) -and ($Filter)"
}
if (-not $IncludeDisabled) {
$params['Filter'] = "($($params['Filter'])) -and (Enabled -eq `$true)"
}
$computers = Get-ADComputer @params
$results = $computers | ForEach-Object {
$computer = $_
$lastLogon = if ($computer.LastLogonDate) { $computer.LastLogonDate } else { "Never" }
$daysSinceLastLogon = if ($lastLogon -ne "Never") { [math]::Round((Get-Date - $lastLogon).TotalDays) } else { $null }
[PSCustomObject]@{
Name = $computer.Name
DNSHostName = $computer.DNSHostName
OperatingSystem = $computer.OperatingSystem
OperatingSystemVersion = $computer.OperatingSystemVersion
LastLogonDate = $lastLogon
DaysSinceLastLogon = $daysSinceLastLogon
Description = $computer.Description
Location = $computer.Location
ManagedBy = $computer.ManagedBy
Created = $computer.Created
Modified = $computer.Modified
Status = switch ($true) {
($daysSinceLastLogon -gt 90) { 'Long Term Inactive' }
($daysSinceLastLogon -gt 30) { 'Inactive' }
($daysSinceLastLogon -le 7) { 'Recently Active' }
default { 'Active' }
}
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved $($results.Count) computers" -Level Info
return $results | Sort-Object -Property LastLogonDate -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve computers: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADDeletedObjects {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[int]$Days = 30,
[Parameter(Mandatory=$false)]
[string[]]$ObjectTypes = @('user', 'computer', 'group'),
[Parameter(Mandatory=$false)]
[string]$SearchBase,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility with additional requirements
$additionalRequirements = @{
RequiredFeatures = @('RSAT-AD-PowerShell', 'AD-Domain-Services')
ServerOnly = $true # Recycle bin operations require Server OS
}
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADDeletedObjects" -AdditionalRequirements $additionalRequirements)) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving deleted AD objects" -Level Info
$cutoffDate = (Get-Date).AddDays(-$Days)
$results = @()
foreach ($objectType in $ObjectTypes) {
$params = @{
Filter = "ObjectClass -eq '$objectType'"
IncludeDeletedObjects = $true
Properties = @(
'Name',
'ObjectClass',
'Deleted',
'LastKnownParent',
'whenChanged',
'whenCreated',
'Description'
)
ErrorAction = 'Stop'
}
if ($SearchBase) {
$params['SearchBase'] = $SearchBase
}
$objects = Get-ADObject @params | Where-Object { $_.Deleted -and $_.whenChanged -gt $cutoffDate }
foreach ($object in $objects) {
$results += [PSCustomObject]@{
Name = $object.Name
ObjectClass = $object.ObjectClass
LastKnownParent = $object.LastKnownParent
DeletedDate = $object.whenChanged
CreatedDate = $object.whenCreated
Description = $object.Description
DaysSinceDeletion = [math]::Round((Get-Date - $object.whenChanged).TotalDays)
Status = switch ($true) {
($object.whenChanged -gt (Get-Date).AddDays(-7)) { 'Recently Deleted' }
($object.whenChanged -gt (Get-Date).AddDays(-30)) { 'Deleted' }
default { 'Long Term Deleted' }
}
}
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved $($results.Count) deleted objects" -Level Info
return $results | Sort-Object -Property DeletedDate -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve deleted objects: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Set-ADUserPassword {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[securestring]$NewPassword,
[Parameter(Mandatory=$false)]
[switch]$Reset,
[Parameter(Mandatory=$false)]
[switch]$RequireChange,
[Parameter(Mandatory=$false)]
[int]$PasswordLength = 16,
[Parameter(Mandatory=$false)]
[switch]$Force
)
# Check function compatibility with additional requirements
$additionalRequirements = @{
RequiredFeatures = @('RSAT-AD-PowerShell')
ServerOnly = $false # Can run on client with RSAT
RequiredPermissions = @('Account Operators', 'Domain Admins')
}
if (-not (Test-ADFunctionCompatibility -FunctionName "Set-ADUserPassword" -AdditionalRequirements $additionalRequirements)) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Setting password for user $Identity" -Level Info
# Verify user exists
$user = Get-ADUser -Identity $Identity -ErrorAction Stop
if ($Reset -and -not $NewPassword) {
# Generate a secure random password
$passwordChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?'
$random = New-Object System.Random
$password = -join (1..$PasswordLength | ForEach-Object { $passwordChars[$random.Next(0, $passwordChars.Length)] })
$NewPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
Write-LogMessage -Message "Generated new password for $Identity" -Level Info
}
if (-not $NewPassword) {
throw "No password provided and Reset not specified"
}
$action = if ($Reset) { "Reset password" } else { "Change password" }
if ($PSCmdlet.ShouldProcess($Identity, $action)) {
Set-ADAccountPassword -Identity $Identity -NewPassword $NewPassword -Reset:$Reset -ErrorAction Stop
if ($RequireChange) {
Set-ADUser -Identity $Identity -ChangePasswordAtLogon $true -ErrorAction Stop
Write-LogMessage -Message "Password change required at next logon for $Identity" -Level Info
}
if ($Reset) {
Write-LogMessage -Message "Password reset successful for $Identity" -Level Info
return [PSCustomObject]@{
Identity = $Identity
Action = "Password Reset"
RequireChange = $RequireChange
Status = "Success"
}
} else {
Write-LogMessage -Message "Password change successful for $Identity" -Level Info
return [PSCustomObject]@{
Identity = $Identity
Action = "Password Change"
RequireChange = $RequireChange
Status = "Success"
}
}
}
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to set password: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADUserLoginHistory {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[int]$Days = 30,
[Parameter(Mandatory=$false)]
[string]$DomainController,
[Parameter(Mandatory=$false)]
[switch]$Detailed,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADUserLoginHistory")) {
throw "This function is not compatible with the current system configuration. See logs for details."
}
try {
Write-LogMessage -Message "Retrieving login history for $Identity" -Level Info
# Verify user exists
$user = Get-ADUser -Identity $Identity -ErrorAction Stop
$startTime = (Get-Date).AddDays(-$Days)
$results = @()
# Get domain controllers if not specified
if (-not $DomainController) {
$dcs = Get-ADDomainController -Filter * -ErrorAction Stop
} else {
$dcs = @(Get-ADDomainController -Identity $DomainController -ErrorAction Stop)
}
foreach ($dc in $dcs) {
try {
$events = Get-WinEvent -ComputerName $dc.HostName -FilterHashtable @{
LogName = 'Security'
ID = 4624 # Successful logon
StartTime = $startTime
} -ErrorAction Stop | Where-Object {
$_.Properties[5].Value -eq $user.SamAccountName
}
foreach ($eventObj in $events) {
$loginInfo = @{
Time = $eventObj.TimeCreated
DomainController = $dc.HostName
User = $user.SamAccountName
LogonType = $eventObj.Properties[10].Value
Workstation = $eventObj.Properties[13].Value
IPAddress = $eventObj.Properties[18].Value
}
if ($Detailed) {
$loginInfo.Add('ProcessName', $eventObj.Properties[9].Value)
$loginInfo.Add('AuthenticationPackage', $eventObj.Properties[10].Value)
$loginInfo.Add('FailureReason', $eventObj.Properties[8].Value)
}
$results += [PSCustomObject]$loginInfo
}
} catch {
Write-LogMessage -Message "Failed to get events from $($dc.HostName): $_" -Level Warning
}
}
if ($ExportPath) {
$results | Export-Csv -Path $ExportPath -NoTypeInformation
Write-LogMessage -Message "Exported results to $ExportPath" -Level Info
}
Write-LogMessage -Message "Retrieved $($results.Count) login events for $Identity" -Level Info
return $results | Sort-Object -Property Time -Descending
} catch {
$errorDetails = Get-ErrorDetail -ErrorRecord $_
Write-LogMessage -Message "Failed to retrieve login history: $($errorDetails.ExceptionMessage)" -Level Error
throw
}
}
function Get-ADUserSID {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Identity,
[Parameter(Mandatory=$false)]
[switch]$IncludeHistory,
[Parameter(Mandatory=$false)]
[string]$ExportPath
)
# Check function compatibility
if (-not (Test-ADFunctionCompatibility -FunctionName "Get-ADUserSID")) {
throw "This function is not compatible with the current system configuration. See logs for details."