-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADtool.ps1
2352 lines (2230 loc) · 107 KB
/
ADtool.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
<#
.AUTHOR
Menno vH (2021)
.DESCRIPTION
AD functionality for users and groups
- Disable/enable accounts
- Unlock accounts
- Reset passwords w/ prompts
- Restore passwords w/ prompts
- Add users to groups
- Remove users from groups
- Easy search; find users/groups based on (parts of) their (user)names
- Easy view; show multiple users and their properties
- Tasklog per user; logs every executed task per user
#>
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$get_comp = Get-ADComputer $env:COMPUTERNAME -Properties OperatingSystem
if ($get_comp.OperatingSystem -like "*Windows Server 2008 R2*" -or $get_comp.OperatingSystem -like "*Windows 7*") {
$MessageBody = "Due to the current version of the Operating system, some actions (e.g. unlocking AD users) may not work. The error message could look like:`n`n'Failed to unlock user account. Insufficient access rights to perform the operation.'`n`nIn order to fix this, one must upgrade the operating system, or install a hotfix from Microsoft. Otherwise, it's necessary to perform these actions via Active Directory..."
$MessageTitle = "Information"
[Microsoft.VisualBasic.Interaction]::MsgBox($MessageBody,'OkOnly,SystemModal,Critical',$MessageTitle) | Out-Null
}
if (!(Test-Path -Path ".\config.ini")) {
$config = New-Item -Path ".\config.ini" -ItemType file
$adm = "!"
} else {
$adm = (Get-Content ".\config.ini" -Filter "[#" | Where-Object {($_.Contains("[#") -and $_.Length -gt 3)})
}
$global:Domains=(Get-ADForest).Domains
if (Test-Path .\images) {
Get-ChildItem .\images -Filter *.png |
Foreach-Object {
$t = "$((Get-Culture).TextInfo.ToTitleCase($_.BaseName))Image"
if (!(Test-Path variable:$t)){
New-Variable -Name "$t" -Value ([System.Drawing.Image]::FromFile($($_.FullName)))
}
}
}
function Fetch-Users {
if ($UserType.ForeColor -eq "Darkgreen") {$type = "-like"} else {$type = "-notlike"}
if ($DomainComboBox.Text -ne "Entire directory") {$Domains = $DomainComboBox.Text} else {$Domains = $global:Domains}
return Start-Job `
-ScriptBlock { `
param ($Type, $PrefixSuffix, $SearchVal, $Domains)
ForEach ($Domain in $Domains) { `
Get-ADUser `
-Server $Domain `
-Filter "SamAccountName $($Type) '$($PrefixSuffix)' -and (Name -like '$($SearchVal)' -or GivenName -like '$($SearchVal)' -or DisplayName -like '$($SearchVal)' -or EmployeeNumber -like '$($SearchVal)' -or EmployeeID -like '$($SearchVal)' -or SamAccountName -like '$($SearchVal)')" `
-Properties Name, DisplayName, SamAccountName, LockedOut, PasswordExpired, PasswordLastSet, GivenName, pwdlastset, PasswordNeverExpires, WhenCreated
}
} -ArgumentList $Type, $PrefixSuffix, $SearchVal, $Domains
}
function Search-Roles {
$UserRolesGrid_QueryLabel.Text = "Preparing fetch"
$AllRoles.Rows.Clear()
$form.Update()
if ($SearchRoleTextBox.Text.Length -lt 3) {
$MessageBody = "This query could take more than 2 minutes!`n`nContinue?"
$MessageTitle = "Confirm choice"
$Result = [Microsoft.VisualBasic.Interaction]::MsgBox($MessageBody,'OkCancel,DefaultButton2,SystemModal,Critical',$MessageTitle)
if ($Result -eq "Cancel") {return}
}
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$Stopwatch.Start()
if ($SearchRoleTextBox.Text.Length -eq 0) {$SearchVal = "*"} else {$SearchVal = "*$($SearchRoleTextBox.Text)*"}
if ($DomainComboBox.Text -ne "Entire directory") {$Domains = $DomainComboBox.Text} else {$Domains = $global:Domains}
$Job = Start-Job -ScriptBlock { `
param($Group, $Domains)
ForEach ($Domain in $Domains) { `
Get-ADGroup `
-Filter "SamAccountName -like '$($Group)' -or Description -like '$($Group)'" `
-Properties SamAccountName, Description, GroupCategory, ManagedBy
}
} -ArgumentList $SearchVal, $Domains
$Stopped = While-Fetch $Job $Stopwatch "search_role"
$status = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
$j = @()
if ($status) {
foreach ($i in $status) {
if ($i.SamAccountName -in $j) {continue} else {$j += $i.SamAccountName}
$AllRoles.Rows.Add($i.SamAccountName,$i.Description,$i.GroupCategory.Value,$i.ManagedBy)
$UserRolesGrid_QueryLabel.Text = "Running ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds))$(if ($Stopped) {' - Stopped by user'}) - Processing data"
$UserRolesGrid_QueryLabel.Refresh()
}
$AllRoles.Sort($AllRoles.Columns['Group'],'Ascending')
$AllRoles.FirstDisplayedScrollingRowIndex = 0
$AllRoles.Refresh()
$AllRoles.CurrentCell = $AllRoles.Rows[0].Cells['Group']
$AllRoles.Rows[0].Selected = $true
}
Remove-Variable j
$Stopwatch.Stop()
$time = $($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)
if ($time -eq 1) {$time = "$($time) second"} else {$time = "$($time) seconds"}
if ($AllRoles.RowCount -eq 1) {
$UserRolesGrid_QueryLabel.Text = "Fetched $($AllRoles.RowCount) row in $($time) - Query: `"$($SearchVal)`""
} elseif ($BlockLabel.Text -ne "x") {
$UserRolesGrid_QueryLabel.Text = "Fetched $($AllRoles.RowCount) rows in $($time) - Query: `"$($SearchVal)`""
} else {
$UserRolesGrid_QueryLabel.Text = "Enter a value and/or press enter to search user. Duration time depends on search value"
Check-Components
}
if ($Stopped) {$UserRolesGrid_QueryLabel.Text = $UserRolesGrid_QueryLabel.Text.Replace("- Query","(stopped by user) - Query")}
}
function Set-Password {
if ($DomainComboBox.Text -ne "Entire directory") {$Domains = $DomainComboBox.Text} else {$Domains = $global:Domains}
if ($PromptUser.Checked) {$action = $true} else {$action = $false}
if ($RestoreRadioButton.Checked) {
return Start-Job `
-Name Restore `
-ScriptBlock { `
param($User, $Old, $New, $Domains, $action)
ForEach($Domain in $Domains) { `
Set-ADAccountPassword `
-Server $Domain `
-Identity $User `
-OldPassword (ConvertTo-SecureString `
-AsPlainText $Old -Force) `
-NewPassword (
ConvertTo-SecureString `
-AsPlainText $New `
-Force
) `
-PassThru | `
Set-ADUser `
-ChangePasswordAtLogon $action
}
} -ArgumentList $UsernameTextbox.Text, $OldPasswordTextBox.Text, $NewPasswordTextBox.Text, $Domains, $action
} else {
return Start-Job `
-Name Reset `
-ScriptBlock {`
param($User, $New, $Domains, $action)
ForEach ($Domain in $Domains) {`
Set-ADAccountPassword `
-Server $Domain `
-Identity $User `
-Reset `
-NewPassword (`
ConvertTo-SecureString `
-AsPlainText $New `
-Force
) `
-PassThru | Set-ADUser -ChangePasswordAtLogon $action}} -ArgumentList $UsernameTextbox.Text, $NewPasswordTextBox.Text, $Domains, $action
}
}
function Save-Account {
if ($DomainComboBox.Text -ne "Entire directory") {$Domains = $DomainComboBox.Text} else {$Domains = $global:Domains}
$Results = New-Object System.Collections.Generic.Dictionary"[Int,String]"
$Errors = New-Object System.Collections.Generic.Dictionary"[Int,String]"
$Table = $Remove = $Add = $Jobs = @()
#Get-ADComputer -Identity "LT54045" -Properties * Enabled OperatingSystem PasswordExpired PasswordNeverExpires PasswordNotRequired isCriticalSystemObject
$StatusLabel.BackColor = "Transparent"
$StatusLabel.ForeColor = "Black"
$SaveButton.Visible = $false
$StatusLabel.FlatAppearance.BorderSize = 0
$StatusLabel.Text = "Processing..."
$StatusLabel.Visible = $true
if ($SaveButton.Text.ToLower().Contains('update')) {
foreach($i in $CurrentRoles.Rows) {
$Exists = $false
foreach($j in $BackupRoles.Rows) {
if ($i.Cells['Group'].Value -eq $j.Cells['Group'].Value) {
$Exists = $true
break
}
}
if (!$Exists) {
$Add += $i.Cells['Group'].Value
}
}
foreach($i in $BackupRoles.Rows) {
$Exists = $false
foreach($j in $CurrentRoles.Rows) {
if ($i.Cells['Group'].Value -eq $j.Cells['Group'].Value) {
$Exists = $true
break
}
}
if (!$Exists) {
$Remove += $i.Cells['Group'].Value
}
}
if ($Remove.Count -gt 0 -or $Add.Count -gt 0) {
$MessageBody = "Proceed with the following role update(s)?`n`nAdd ($($Add.Count))" + $(if($Add.Count -gt 0) {":`n$($Add | Out-String)"} else {"`n"}) + "`nRemove ($($Remove.Count))" + $(if($Remove.Count -gt 0) {":`n$($Remove | Out-String)"})
$MessageTitle = "Confirm choice"
$Result = [Microsoft.VisualBasic.Interaction]::MsgBox($MessageBody,'YesNo,DefaultButton2,SystemModal,Critical',$MessageTitle)
}
}
$StatusLabel.Text = "Running $($Jobs.Count) job$(if ($Jobs.Count -ne 1) {"s"}) ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds))"
$StatusLabel.Refresh()
# reset/restore password
if (($NewPasswordTextBox.Text.Length -gt 0 -and $ResetRadioButton.Checked) -or ($NewPasswordTextBox.Text.Length -0 -and $OldPasswordTextBox.Text.Length -gt 0 -and $RestoreRadioButton.Checked) -or ($PrompUser.Checked -and $NewPasswordTextBox.Text.Length -gt 0 -and !$SaveButton.Text.ToLower().Contains('disable'))) {
$Jobs += Set-Password
$StatusLabel.Text = "Running $($Jobs.Count) job$(if ($Jobs.Count -ne 1) {"s"})"
$StatusLabel.Refresh()
}
#enable/disable user
if ($SaveButton.Text.ToLower().Contains('able')) {
if ($SaveButton.Text.ToLower().Contains('disable')) {$Type = "Disable"} else {$Type = "Enable"}
switch ($Type) {
"Enable" {$Jobs += Start-Job -Name Enable -ScriptBlock {param($User,$Domains); ForEach ($Domain in $Domains) {Enable-ADAccount -Server $Domain -Identity $User}} -ArgumentList $UsernameTextbox.Text, $Domains}
"Disable" {$Jobs += Start-Job -Name Disable -ScriptBlock {param($User,$Domains); ForEach($Domain in $Domains) {Disable-ADAccount -Server $Domain -Identity $User}} -ArgumentList $UsernameTextbox.Text, $Domains}
}
$StatusLabel.Text = "Running $($Jobs.Count) job$(if ($Jobs.Count -ne 1) {"s"})"
$StatusLabel.Refresh()
}
if ((Get-ADUser -Identity $UsernameTextbox.Text -Properties LockedOut).LockedOut -eq $true -or ($SaveButton.Text.ToLower().Contains('unlock') -or (($NewPasswordTextBox.Text.Length -gt 0 -or $PromptUser.Checked) -and !$SaveButton.Text.ToLower().Contains('disable')))) {
#unlock user
if (!$SaveButton.Text.ToLower().Contains('unlock') -or ($PromptUser.Checked -and !$SaveButton.Text.ToLower().Contains('unlock'))) {
$Addition = " (additionally)"
}
$Jobs += Start-Job -Name Unlock -ScriptBlock {param($User,$Domains); ForEach($Domain in $Domains) {Unlock-ADAccount -Server $Domain -Identity $User}} -ArgumentList $UsernameTextbox.Text, $Domains
$StatusLabel.Text = "Running $($Jobs.Count) job$(if ($Jobs.Count -ne 1) {"s"})"
$StatusLabel.Refresh()
}
if ($PromptUser.Checked -and $NewPasswordTextBox.Text.Length -eq 0 -and !$SaveButton.Text.ToLower().Contains('disable')) {
$Jobs += Start-Job -Name Prompt -ScriptBlock {param($User,$Domains); ForEach ($Domain in $Domains) {Set-ADUser -Server $Domain -Identity $User -ChangePasswordAtLogon $true}} -ArgumentList $UsernameTextbox.Text, $Domains
}
if ($SaveButton.Text.ToLower().Contains('update')) {
if ($Result -eq "Yes") {
$Actions = $Add + $Remove
foreach($Group in $Actions){
if ($Group -in $Add) {
$Jobs += Start-Job `
-Name "+$($Group)" `
-ScriptBlock {`
param($User, $Group, $Domains)
ForEach ($Domain in $Domains) { `
Add-ADGroupMember `
-Server $Domain `
-Identity $User `
-Members $Group
}
} -ArgumentList $Group, $UsernameTextbox.Text, $Domains
} else {
$Jobs += Start-Job `
-Name "-$($Group)" `
-ScriptBlock { `
param( $User, $Group, $Domains)
ForEach ($Domain in $Domains) {`
Remove-ADGroupMember `
-Server $Domain `
-Identity $User `
-Members $Group `
-Confirm:$false
}
} -ArgumentList $Group, $UsernameTextbox.Text, $Domains
}
$StatusLabel.Text = "Running $($Jobs.Count) job$(if ($Jobs.Count -ne 1) {"s"})"
$StatusLabel.Refresh()
}
}
}
$Completed = $false
while (-not $Completed) {
$JobsInProgress = ($Jobs | Where-Object {$_.State -match ‘running’}).ChildJobs.Count
$StatusLabel.Text = "Running $($JobsInProgress) job$(if ($JobsInProgress -ne 1) {"s"})"
$StatusLabel.Refresh()
if ($JobsInProgress -eq 0) {$Completed = $true}
}
if ($PromptUser.Checked) {$action = " with prompt to reset"} else {$action = ""}
foreach($Job in $Jobs) {
$StatusLabel.Text = "Fetching $($Jobs.Count) job$(if ($JobsInProgress -ne 1) {"s"})"
$StatusLabel.Refresh()
if ($Job.Name.Substring(0,1) -eq "+" -or $Job.Name.Substring(0,1) -eq "-") {
$Name = $Job.Name.Substring(1)
try{
Receive-Job -Job $Job -Wait -ErrorAction Stop;
$Results.Add($Results.Count + 1,"$($Job.Name.Substring(0,1).Replace("+", "Added to").Replace("-", "Removed from ")) '$($Name)'")
$Table += [Pscustomobject]@{Result = "Success";Task = "$($Job.Name.Substring(0,1).Replace("+", "Added to").Replace("-", "Removed from ")) '$($Name)'";Error = ""}
} catch {
$Errors.Add($Errors.Count + 1, "Failed to $($Job.Name.Substring(0,1).Replace("+", "Add to").Replace("-", "Remove from ")) '$($Name)':`n$($_)")
$Table += [Pscustomobject]@{Result = "Fail";Task = "Failed to $($j.Name.Substring(0,1).Replace("+", "add to").Replace("-", "remove from ")) '$($Name)'";Error = "$_"}
}
} else {
$Name = $Job.Name
switch ($Name) {
"Unlock" {$Description= "$($Name) account$($Addition)"; $Success="Account $($Name.ToLower())ed$($Addition)"; $Failure="Failed to $($Name.ToLower()) account$($Addition)"}
"Reset" {$Description= "$($Name) password$($action)"; $Success="Password has been $($Name.ToLower())$($action)";$Failure="Failed to $($Name.ToLower()) password$($action)"}
"Restore" {$Description= "$($Name) password$($action)"; $Success="Password has been $($Name.ToLower())d$($action)";$Failure="Failed to $($Name.ToLower()) password$($action)"}
"Enable" {$Description= "$($Name) account"; $Success="Account $($Name.ToLower())d";$Failure="Failed to $($Name.ToLower()) account"}
"Disable" {$Description= "$($Name) account"; $Success="Account $($Name.ToLower())d";$Failure="Failed to $($Name.ToLower()) password"}
"Prompt" {$Description= "$($Name) user to change password"; $Success="User will be $($Name.ToLower())ed to change password";$Failure="Failed to $($Name.ToLower()) user to change password"}
}
try{
Receive-Job -Job $Job -Wait -ErrorAction Stop
$Results.Add($Results.Count + 1,"$($Success)")
$Table += [Pscustomobject]@{Result = "Success";Task = "$($Success)";Error = ""}
} catch {
$Errors.Add($Errors.Count + 1, "$($Failure):`n$($_)`n")
$Table += [Pscustomobject]@{Result = "Fail";Task = "$($Failure)";Error = "$_"}
}
}
}
#get user status
$Job = Start-Job `
-ScriptBlock {`
param ($User, $Domains)
ForEach ($Domain in $Domains) { `
Get-ADUser `
-Server $Domain `
-Identity $User `
-Properties * | `
Select LockedOut, Enabled, PasswordLastSet, PasswordExpired, pwdlastset, PasswordNeverExpires, WhenCreated
}
} -ArgumentList $UsernameTextbox.Text, $Domains | `
Wait-Job
$Status = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
write-host $Status
$Job = (Start-Job -ScriptBlock {(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days}) | Wait-Job
$MaxPwdAge = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
$dgv.CurrentRow.Cells['Locked'].Value = $Status.LockedOut
$dgv.CurrentRow.Cells['Password last set'].Value = $Status.PasswordLastSet
if ($status.PasswordNeverExpires -eq 1) {
$dgv.CurrentRow.Cells['Password expires'].Value = $null
} else {
if ($status.PasswordLastSet.Length -gt 0) {
$dgv.CurrentRow.Cells['Password expires'].Value = [datetime]($dgv.CurrentRow.Cells['Password last set'].Value).AddDays($MaxPwdAge)
} else {
$dgv.CurrentRow.Cells['Password expires'].Value = [datetime]($i.WhenCreated).AddDays($MaxPwdAge)
}
}
$dgv.CurrentRow.Cells['Enabled'].Value = $Status.Enabled
if ($Status.Enabled) {$EnableCheckBox.Text = "Disable"} else {$EnableCheckBox.Text = "Enable"}
$EnableCheckBox.Checked = $false
$Total = $Results.Values | Out-string
if ($Errors.Count -gt 0 -and $Total.Length -ne 0) {$Total += "`n"}
$Total += $Errors.Values | Out-string
if ($Errors.Count -eq $Jobs.Count) {
$StatusLabel.ForeColor = "White"
$StatusLabel.BackColor = "Red"
} elseif ($Errors.Count -gt 0) {
$StatusLabel.ForeColor = "Black"
$StatusLabel.BackColor = "Orange"
} else {
$StatusLabel.ForeColor = "Black"
$StatusLabel.BackColor = "Lightgreen"
}
$StatusLabel.FlatAppearance.BorderSize = 1
$StatusLabel.Text = "Show report"
$StatusLabelTotal.Text = $Total
if ($Total.Length -gt 0) {
try {
$path = ".\tasklog"
If(!(test-path $path)) {
New-Item -ItemType Directory -Force -Path $path
}
$file_path = "$($UsernameTextbox.Text).txt"
if (!(Test-Path -Path $(Join-Path -Path $path $file_path))) {
New-Item -Path $(Join-Path -Path $path $file_path) -ItemType File
$s = ""
} else {
$s = "`r`n"
}
$Task = "Task$(if ($Jobs.Count -ne 1){"s"}) ($($Jobs.Count))"
$Error = "Error$(if ($Errors.Count -ne 1){"s"}) ($($Errors.Count))"
"$($s)$("#"*35) $((Get-Date).ToString("dd.MM.yyyy - HH.mm.ss")) $("#"*35)`r`n`r`n" + ($Table | Sort-Object "Result", "Task" | Format-Table -Wrap -Property @{e='Result';Width=10}, @{e='Task';label=$Task;Width=40}, @{e='Error';label=$Error;Width=100} | Out-String).Trim() | Out-File -FilePath $(Join-Path -Path $path $file_path) -Append
} catch {}
}
$StatusList = @($Status.PasswordExpired, !$Status.Enabled, $Status.LockedOut)
for ($Item=0; $Item -lt $StatusList.Count; $Item++){
switch ($Item) {
0 {$Column = "Password expires"}
1 {$Column = "Enabled"}
2 {$Column = "Locked"}
}
if (($Item -eq 0 -and $Status.pwdlastset -eq 0) -or ($StatusList[$Item] -and $StatusList[$Item] -ne $null)) {
$dgv.SelectedRows[0].Cells[$Column].Style.BackColor = "Orange"
$dgv.SelectedRows[0].Cells[$Column].Style.ForeColor = "Black"
$dgv.SelectedRows[0].Cells[$Column].Style.SelectionBackColor = "Red"
$dgv.SelectedRows[0].Cells[$Column].Style.SelectionForeColor = "White"
} else {
$dgv.SelectedRows[0].Cells[$Column].Style.BackColor = $dgv.SelectedRows[0].Cells['Name'].Style.BackColor
$dgv.SelectedRows[0].Cells[$Column].Style.ForeColor = $dgv.SelectedRows[0].Cells['Name'].Style.ForeColor
$dgv.SelectedRows[0].Cells[$Column].Style.SelectionBackColor = "Yellow"
$dgv.SelectedRows[0].Cells[$Column].Style.SelectionForeColor = "Blue"
}
}
}
function Switch-View {
$list = @($UserGrid, $UserRolesGrid, $UserPropertiesGrid, $GroupGrid)
switch ($UsernameLabel.Text) {
"Object" {
#user will be selected
$UsernameLabel.Text = "User"
$UserType.Visible = $true
$SearchGroupTextBox.Visible = $false
$SearchUserTextBox.Visible = $true
if ($UsernameTextbox.Text.Length -gt 0) {$InfoButton.Visible = $RoleButton.Visible = $true} else {$InfoButton.Visible = $RoleButton.Visible = $false}
$GroupGrid.Visible = $false; $UserGrid.Visible = $true
$GroupsTextbox.Visible = $UserRolesGrid.Visible = $false
$UsernameTextbox.Visible = $true
$SearchUserTextBox.Focus()
}
"Printer" {$UsernameLabel.Text = "Object"}
"Group" {$UsernameLabel.Text = "Printer"}
"User" {
$UsernameLabel.Text = "Group"
$UserType.Visible = $InfoButton.Visible = $RoleButton.Visible = $false
$SearchUserTextBox.Visible = $UserRolesGrid.Visible = $false
$SearchGroupTextBox.Visible = $true
$UserGrid.Visible = $false; $GroupGrid.Visible = $true
$UsernameTextbox.Visible = $false
$GroupsTextbox.Visible = $true
$SearchGroupTextBox.Focus()
}
}
}
function Check-Components {
$vars = @($OldPasswordTextBox, $NewPasswordTextBox, $SaveButton)
if ($UsernameTextbox.Text.Length -eq 0) {
foreach($i in $vars) {
$i.Visible = $false
}
$SaveButton.Text = ""
$RestoreRadioButton.Visible = $ResetRadioButton.Visible = $RoleButton.Visible = $InfoButton.Visible = $UserRolesGrid.Visible = $UserPropertiesGrid.Visible = $EnableCheckBox.Visible = $false
if (!(Test-Path variable:$userrolesImage)){
$RoleButton.Image = $userrolesImage
$RoleButton.Text = ""
} else {
$RoleButton.Text = "R"
}
if (!(Test-Path variable:$UserinfoImage)){
$InfoButton.Image = $UserinfoImage
$InfoButton.Text = ""
} else {
$InfoButton.Text = " I"
}
$RoleButton.ForeColor = "Black"
$dgv.Visible = $true
} else {
if ($dgv.SelectedRows[0].Cells['Locked'].Value -eq $false) {$locked = $false} else {$locked = $true}
$RoleButton.Visible = $InfoButton.Visible = $EnableCheckBox.Visible = $true
$RestoreRadioButton.Visible = $ResetRadioButton.Visible = $true
if ($RestoreRadioButton.Checked) {
for ($i = 0; $i -lt 3; $i++) {if ($i -ne 2) {$vars[$i].Visible = $true} else {$vars[$i].Visible = $false}}
if (!$locked -and $vars[0].Text.Length -eq 0 -and $vars[1].Text.Length -eq 0) {$res = 1} #invisible
if ($locked -and $vars[0].Text.Length -eq 0 -and $vars[1].Text.Length -eq 0) {$res = 2} #unlock
if ($vars[0].Text.Length -gt 0 -and $vars[1].Text.Length -gt 0) {$res = 3} #restore
} else {
for ($i = 0; $i -lt 3; $i++) {if ($i -gt 0 -and $i -ne 2) {$vars[$i].Visible = $true} else {$vars[$i].Visible = $false}}
if (!$locked -and $vars[1].Text.Length -eq 0) {$res = 1} #invisible
if ($locked -and $vars[1].Text.Length -eq 0) {$res = 2} #unlock
if ($vars[1].Text.Length -gt 0) {$res = 4} #reset
}
if ($EnableCheckBox.Checked -and $EnableCheckBox.Text -eq "Disable" -and $res -le 2) {$res = 5}
if ($EnableCheckBox.Checked -and $EnableCheckBox.Text -eq "Enable" -and $res -eq 1) {$res = 5}
}
switch ($res) {
1 {$SaveButton.Visible = $false}
2 {$SaveButton.Visible = $true; $SaveButton.Text = "Unlock"; if ($EnableCheckBox.Checked) {$SaveButton.Text += " and $($EnableCheckBox.Text.toLower())"}}
3 {$SaveButton.Visible = $true; $SaveButton.Text = "Restore password"; if ($locked -and !$EnableCheckBox.Checked -and $EnableCheckBox.Text -eq "Disable") {$SaveButton.Text += " and unlock"} elseif ($EnableCheckBox.Checked) {$SaveButton.Text += " and $($EnableCheckBox.Text.toLower())"}}
4 {$SaveButton.Visible = $true; $SaveButton.Text = "Reset password"; if ($locked -and !$EnableCheckBox.Checked -and $EnableCheckBox.Text -eq "Disable") {$SaveButton.Text += " and unlock"} elseif ($EnableCheckBox.Checked) {$SaveButton.Text += " and $($EnableCheckBox.Text.toLower())"}}
5 {$SaveButton.Visible = $true; $SaveButton.Text = $EnableCheckBox.Text}
}
if ($PromptUser.Checked -and $UsernameTextbox.Text.Length -gt 0) {
if ($SaveButton.Visible -eq $false) {$SaveButton.Visible = $true;$SaveButton.Text = "Prompt"} else {$SaveButton.Text = "$($SaveButton.Text.Replace(" and", ", ")) and Prompt"}
}
$change = $false
foreach ($i in $CurrentRoles.Rows) {
foreach ($j in $BackupRoles.Rows) {
$in = $false
if ($i.Cells['Group'].Value -eq $j.Cells['Group'].Value){
$in = $true
break
}
}
if (!$in) {
$change = $true
break
}
}
if ($CurrentRoles.RowCount -ne $BackupRoles.RowCount) {
$change = $true
}
if ($change) {
$SaveButton.Text = $SaveButton.Text.Replace(" and",", ")
if ($SaveButton.Visible){
$SaveButton.Text += " and update"
} else {
$SaveButton.Visible = $true
$SaveButton.Text = "Update"
}
}
$StatusLabel.BackColor = "Transparent"
$StatusLabel.Text = ""
$StatusLabel.Visible = $false
}
function Set-Color ($item) {
$dgv.Rows[$dgv.RowCount -1].Cells[$item].Style.BackColor = "Orange"
$dgv.Rows[$dgv.RowCount -1].Cells[$item].Style.ForeColor = "Black"
$dgv.Rows[$dgv.RowCount -1].Cells[$item].Style.SelectionBackColor = "Red"
$dgv.Rows[$dgv.RowCount -1].Cells[$item].Style.SelectionForeColor = "White"
}
function Set-Colors ($val) {
for ($i=0;$i -lt $dgv.RowCount;$i++){
if ($($i%2) -eq 1) {
$dgv.Rows[$i].DefaultCellStyle.BackColor = $val
} else {
$dgv.Rows[$i].DefaultCellStyle.BackColor = "White"
}
}
}
function While-Fetch ($Job, $Stopwatch, $Type) {
$Stopped = $false
switch ($Type) {
"Refresh-Users" {$Label = $UserGrid_QueryLabel}
"Refresh-Groups" {$Label = $GroupGrid_QueryLabel}
"info" {$Label = $UserRolesGrid_QueryLabel}
"search_role" {$Label = $UserRolesGrid_QueryLabel}
}
while ($Job.State -eq [System.Management.Automation.JobState]::Running) {
$Label.Text = "Running ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)) - Fetching data"
if ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)%10 -eq 0 -and $run -eq 0) {
$Stopwatch.Stop()
$MessageBody = "Abort query?"
$MessageTitle = "Confirm choice"
$Result = [Microsoft.VisualBasic.Interaction]::MsgBox($MessageBody,'YesNo,DefaultButton2,SystemModal,Critical',$MessageTitle)
if ($Result -eq "No") {$run = 1} else {Stop-Job -Job $Job;$Stopped = $true}
$Stopwatch.Start()
} elseif ($(($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)%10 -gt 0)) {$run = 0}
$Label.Refresh()
}
return $Stopped
}
function Refresh-Users {
if ($SearchUserTextBox.Text.Replace("*","").Length -eq 0) {$SearchVal = "*"} else {$SearchVal = "*$($SearchUserTextBox.Text)*"}
$UserRolesGrid.Visible = $UserPropertiesGrid.Visible = $false
$UserGrid.Visible = $true
if (!(Test-Path variable:$UserinfoImage)){
$InfoButton.Image = $UserinfoImage
} else {
$InfoButton.Text = " I"
}
$UserGrid_QueryLabel.Text = "Preparing fetch"
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$Stopwatch.Start()
$dgv.Rows.Clear()
$BackupRoles.Rows.Clear()
$CurrentRoles.Rows.Clear()
$UsernameTextbox.Text = ""
$EnableCheckBox.Text = ""
$EnableCheckBox.Checked = $false
Check-Components
$i = 0
if ($BlockLabel.Text -ne "x") {
$MaxPwdAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
try{
if (Test-Path -Path ".\config.ini") {
$adm = (Get-Content ".\config.ini" -Filter "[#" | Where-Object {($_.Contains("[#") -and $_.Length -gt 3)})
} elseif ($UserType.Text -ne "!" -and $UserType.Text.Length -gt 0) {
$adm = $UserType.Text
}
if ($adm.Length -gt 0) {
$PrefixSuffix = $($adm.Substring(4, $adm.Length -4).Replace("[$]",""))
if ($PrefixSuffix.Length -gt 0) {
if ($adm.Substring(0, 4) -eq "[#l]") {
$PrefixSuffix = "$($PrefixSuffix)*"
} elseif ($adm.Substring(0,4) -eq "[#r]") {
$PrefixSuffix = "*$($PrefixSuffix)"
} elseif ($adm.Substring(0,4) -eq "[#c]") {
$PrefixSuffix = "*$($PrefixSuffix)*"
}
}
}
$Job = Fetch-Users
$Stopped = While-Fetch $Job $Stopwatch "Refresh-Users"
$users = Receive-Job -Job $Job
}catch{$UserGrid_QueryLabel.Text = "Error occurred: $Error[0]"}
if ($users) {
foreach($i in $users) {
if ($UserType.ForeColor -ne "Darkgreen" -and $UserType.ForeColor -ne "Orange" -and $i.SamAccountName -like $PrefixSuffix) {continue}
if ($i.PasswordNeverExpires -eq 1) {
$dgv.Rows.Add($i.DisplayName,$i.Name,$i.SamAccountName,$i.LockedOut, $i.Enabled, $null, $i.PasswordLastSet)
} elseif ($i.PasswordLastSet.Length -gt 0) {
$dgv.Rows.Add($i.DisplayName,$i.Name,$i.SamAccountName,$i.LockedOut, $i.Enabled, [datetime]($i.PasswordLastSet).AddDays($MaxPwdAge), $i.PasswordLastSet)
} else {
$dgv.Rows.Add($i.DisplayName,$i.Name,$i.SamAccountName,$i.LockedOut, $i.Enabled, [datetime]($i.WhenCreated).AddDays($MaxPwdAge), $i.PasswordLastSet)
}
if ($i.PasswordExpired -or $i.pwdlastset -eq 0) {Set-Color "Password expires"}
if (!$i.Enabled) {Set-Color "Enabled"}
if ($i.LockedOut) {Set-Color "Locked"}
$dgv.AutoResizeRow($dgv.RowCount-1, [System.Windows.Forms.DataGridViewAutoSizeRowMode]::AllCellsExceptHeader)
$UserGrid_QueryLabel.Text = "Running ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds))$(if ($Stopped) {' - Stopped by user'}) - Processing data"
$UserGrid_QueryLabel.Refresh()
}
}
}
$Stopwatch.Stop()
$time = $($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)
if ($time -eq 1) {$time = "$($time) second"} else {$time = "$($time) seconds"}
if ($dgv.RowCount -eq 1) {
$UserGrid_QueryLabel.Text = "Fetched $($dgv.RowCount) row in $($time) - Query: `"$($SearchVal)`""
} elseif ($BlockLabel.Text -ne "x") {
$UserGrid_QueryLabel.Text = "Fetched $($dgv.RowCount) rows in $($time) - Query: `"$($SearchVal)`""
} else {
$UserGrid_QueryLabel.Text = "Enter a value and/or press enter to search user. Duration time depends on search value"
Check-Components
}
if ($Stopped) {$UserGrid_QueryLabel.Text = $UserGrid_QueryLabel.Text.Replace("- Query","(stopped by user) - Query")}
$BlockLabel.Text = ""
$dgv.Sort($dgv.Columns['Username'],'Ascending')
if ($dgv.RowCount -eq 1) {
$dgv.FirstDisplayedScrollingRowIndex = 0
$dgv.Refresh()
if($DisplayButton.Text -eq "◨") {
$dgv.CurrentCell = $dgv.Rows[0].Cells['Display name']
} else {
$dgv.CurrentCell = $dgv.Rows[0].Cells['Name']
}
$dgv.Rows[0].Selected = $true
$UsernameTextbox.Text = $dgv.Rows[0].Cells['Username'].Value
if ($dgv.Rows[0].Cells['Enabled'].Value -eq $true) {$EnableCheckBox.Text = "Disable"} else {$EnableCheckBox.Text = "Enable"}
} else {
$dgv.ClearSelection()
$UsernameTextbox.Text = ""
}
}
function Refresh-Groups {
$BlockLabel.Text = "x"
if ($DomainComboBox.Text -ne "Entire directory") {$Domains = $DomainComboBox.Text} else {$Domains = $global:Domains}
if ($SearchUserTextBox.Text.Replace("*","").Length -eq 0) {$SearchVal = "*"} else {$SearchVal = "*$($SearchUserTextBox.Text)*"}
if (!(Test-Path variable:$GroupinfoImage)){$InfoGroupButton.Image = $GroupinfoImage} else {$InfoGroupButton.Text = " I"}
$GroupGrid_QueryLabel.Text = "Preparing fetch"
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$Stopwatch.Start()
$BackupGroups.Rows.Clear()
$AllGroups.Rows.Clear()
$AllMembers.Rows.Clear()
$GroupsTextbox.Text = ""
$BlockLabel.Text = "y"
$i = 0
if ($SearchGroupTextBox.Text.Length -eq 0) {$SearchVal = "*"} else {$SearchVal = "*$($SearchGroupTextBox.Text)*"}
$Job = Start-Job -ScriptBlock {param($Group,$Domains); ForEach($Domain in $Domains) {Get-ADGroup -Server $Domain -Filter "SamAccountName -like '$($Group)' -or Description -like '$($Group)'" -Properties SamAccountName, Description, GroupCategory, ManagedBy}} -ArgumentList $SearchVal, $Domains
$Stopped = While-Fetch $Job $Stopwatch "Refresh-Groups"
$status = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
if ($status) {
foreach ($i in $status) {
$AllGroups.Rows.Add($i.SamAccountName,$i.Description,$i.GroupCategory.Value,$i.ManagedBy)
$GroupGrid_QueryLabel.Text = "Running ($($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds))$(if ($Stopped) {' - Stopped by user'}) - Processing data"
$GroupGrid_QueryLabel.Refresh()
}
$AllGroups.Sort($AllGroups.Columns['Group'],'Ascending')
$AllGroups.FirstDisplayedScrollingRowIndex = 0
$AllGroups.Refresh()
$AllGroups.CurrentCell = $AllGroups.Rows[0].Cells['Group']
$AllGroups.Rows[0].Selected = $true
$GroupsTextbox.Text = $AllGroups.Rows[0].Cells['Group'].Value
}
$Stopwatch.Stop()
$time = $($Stopwatch.Elapsed.Minutes * 60 + $Stopwatch.Elapsed.Seconds)
if ($time -eq 1) {$time = "$($time) second"} else {$time = "$($time) seconds"}
if ($AllGroups.RowCount -eq 1) {$GroupGrid_QueryLabel.Text = "Fetched $($AllGroups.RowCount) row in $($time) - Query: `"$($SearchVal)`""} elseif ($BlockLabel.Text -ne "x") {$GroupGrid_QueryLabel.Text = "Fetched $($AllGroups.RowCount) rows in $($time) - Query: `"$($SearchVal)`""} else {$GroupGrid_QueryLabel.Text = "Enter a value and/or press enter to search user. Duration time depends on search value"}
if ($Stopped) {$GroupGrid_QueryLabel.Text = $GroupGrid_QueryLabel.Text.Replace("- Query","(stopped by user) - Query")}
$BlockLabel.Text = ""
}
function Fetch-UserInfo {
$UserProperties.Rows.Clear()
$Job = Start-Job `
-ScriptBlock {`
param ($User)
Get-ADUser `
-Identity $User `
-Properties `
GivenName,
Surname,
DisplayName,
Name,
SamAccountName,
EmployeeID,
EmployeeNumber,
employeeType,
City,
EmailAddress,
DoesNotRequirePreAuth,
Enabled,
LockedOut,
LockoutTime,
LogonCount,
LogonWorkstations,
mail,
mailNickname,
Manager,
MobilePhone,
Modified,
ModifyTimeStamp,
Office,
OfficePhone,
Organization,
PasswordExpired,
PasswordLastSet,
PasswordNeverExpires,
PasswordNotRequired,
physicalDeliveryOfficeName,
PostalCode,
ProtectedFromAccidentalDeletion,
ProfilePath,
showInAddressBook,
SmartcardLogonRequired,
State,
StreetAddress,
targetAddress,
UserPrincipalName,
whenCreated,
whenChanged,
HomeDirectory,
HomeDrive,
HomePhone,
Fax,
Title,
Department
} -ArgumentList $UsernameTextBox.Text | Wait-Job
$status = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
$list = @(@("Given Name",$status.GivenName),
@("Surname",$status.Surname),
@("Display name",$status.DisplayName),
@("Name",$status.Name),
@("Username",$status.SamAccountName),
@("User principal name",$status.UserPrincipalName),
@("Employee ID",$status.EmployeeID),
@("Employee number",$status.EmployeeNumber),
@("Employee type",$status.EmployeeType),
@("Manager",$status.Manager),
@("Department",$status.Department),
@("Title",$status.Title),
@("Home phone",$status.HomePhone),
@("Mobile phone",$status.MobilePhone),
@("Office phone",$status.OfficePhone),
@("Email address",$status.EmailAddress),
@("Mail",$status.mail),
@("Mail nickname",$status.mailNickname),
@("Home directory",$status.HomeDirectory),
@("Home drive",$status.HomeDrive),
@("Organization",$status.Organization),
@("Office",$status.Office),
@("Physical delivery office name",$status.physicalDeliveryOfficeName),
@("State",$status.State),
@("Street address",$status.StreetAddress),
@("Postal code",$status.PostalCode),
@("City",$status.City),
@("Created",$status.whenCreated),
@("Changed",$status.whenChanged),
@("Enabled",$status.Enabled),
@("Fax",$status.Fax),
@("Locked",$status.LockedOut),
@("Lockout time",$status.LockoutTime),
@("Logon count",$status.LogonCount),
@("No pre-auth required",$status.DoesNotRequirePreAuth),
@("Password expired",$status.PasswordExpired),
@("Password last set",$status.PasswordLastSet),
@("Password never expires",$status.PasswordNeverExpires),
@("Password not required",$status.PasswordNotRequired),
@("Profile path",$status.ProfilePath),
@("Protected from accidental deletion",$status.ProtectedFromAccidentalDeletion),
@("Modified",$status.Modified),
@("Modify timestamp",$status.ModifyTimeStamp),
@("Logon workstations",$status.LogonWorkstations),
@("Show in address book",$status.showInAddressBook),
@("Smartcard logon required",$status.SmartcardLogonRequired),
@("Target address",$status.targetAddress))
foreach($i in $list) {
if ($i[1] -is [Object[]] -or $i[1] -is [System.Collections.ArrayList]) {
$UserProperties.Rows.Add($i[0], ($i[1] | Out-String))
} elseif ($i[1] -ne $null) {
$UserProperties.Rows.Add($i[0], "$($i[1])")
} else {$UserProperties.Rows.Add($i[0], "")}
}
foreach($i in $CheckBoxGrid.Rows){
foreach($j in $UserProperties.Rows) {
if ($j.Cells[0].Value -eq $i.Cells[1].Value) {
$j.Visible = $i.Cells[0].Value
break
}
}
}
foreach($i in $UserProperties.Rows) {
if ($i.Visible) {
$i.Selected = $true
break
}
}
$CheckBoxButton.Visible = $false
}
function Fetch-Roles {
if ($CurrentRoles.RowCount -eq 0) {
$CurrentRoles.Rows.Clear()
$BackupRoles.Rows.Clear()
}
$UserGrid.Visible = $UserPropertiesGrid.Visible = $false
$UserRolesGrid.Visible = $true
if ($CurrentRoles.RowCount -eq 0) {
$UserRolesGridStatusLabel.Text = ""
$UserRolesGridStatusLabel.BackColor = "Transparent"
$Job = Start-Job `
-ScriptBlock {`
param($arg0)
$(Get-ADUser `
-Filter "SamAccountName -eq '$($arg0)'" `
-Properties MemberOf
).memberof | `
Get-ADGroup `
-Properties SamAccountName, Description, GroupCategory, ManagedBy
} -ArgumentList $UsernameTextbox.Text | `
Wait-Job
$status = try{Receive-Job -Job $Job -ErrorAction Stop} catch {"$_"}
if ($status) {
foreach ($i in $status) {
$CurrentRoles.Rows.Add($i.SamAccountName,$i.Description,$i.GroupCategory.Value,$i.ManagedBy)
$BackupRoles.Rows.Add($i.SamAccountName,$i.Description,$i.GroupCategory.Value,$i.ManagedBy)
}
$BackupRoles.Refresh()
$CurrentRoles.Sort($CurrentRoles.Columns['Group'],'Ascending')
$CurrentRoles.FirstDisplayedScrollingRowIndex = 0
$CurrentRoles.Refresh()
$CurrentRoles.CurrentCell = $CurrentRoles.Rows[0].Cells['Group']
$CurrentRoles.Rows[0].Selected = $true
}
}
$BlockLabel.Text = ""
}
function Set-AdminPreSuffix {
if ($AdminTextBox.Text.Length -gt 0){
$PrefixSuffix = $AdminTextBox.Text.Trim("*")
$AdminTextBox.Text = $PrefixSuffix
if ($LeftRadioButton.Checked) {$UserType.Text = "$($AdminTextBox.Text)*"; $adm = "[#l]$($PrefixSuffix)";}
if ($CenterRadioButton.Checked) {$UserType.Text = $adm = "*$($AdminTextBox.Text)*";$adm = "[#c]$($PrefixSuffix)";}
if ($RightRadioButton.Checked) {$UserType.Text = $adm = "*$($AdminTextBox.Text)";$adm = "[#r]$($PrefixSuffix)";}
if ($UserType.Text.Length -gt 5) {$UserType.Text = $UserType.Text.SubString(0,4)+".."}
$list = @()
if ($adm.Length -gt 0) {$list += $adm}
foreach ($i in $CheckBoxGrid.Rows) {
$list += [int]$i.Cells[0].Value
}
Set-Content -Path ".\config.ini" -Value ($list | Out-String)
if (($($UserType.Text -ne "!" -and $UserType.ForeColor -eq "Darkgreen") -or ($UserType.ForeColor -ne "Darkgreen" -and $UserType.ForeColor -ne "Orange"))) {
if ($UserType.ForeColor -ne "Darkgreen" -and $UserType.ForeColor -ne "Orange" -and $SearchUserTextBox.Text.Length -eq 0) {
$BlockLabel.Text = "x"
}
Refresh-Users
$BlockLabel.Text = ""; $SearchUserTextBox.Focus()
}
}
}
$form = New-Object System.Windows.Forms.Form
$form.Text = ”ADtool”
$form.StartPosition = "CenterScreen"
$Font = New-Object System.Drawing.Font("Calibri",11)
$form.Font = $Font
$form.AutoSize = $true
$form.Width = 744
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$UserGrid = New-Object System.Windows.Forms.GroupBox
$UserGrid.Size=New-Object System.Drawing.Size(400,400)
$UserGrid.Width = $form.Width
$UserGrid.Dock = 'Top'
$form.Controls.Add($UserGrid)
$UserRolesGrid = New-Object System.Windows.Forms.GroupBox
$UserRolesGrid.Size=New-Object System.Drawing.Size($UserGrid.Size)
$UserRolesGrid.Visible = $false
$UserRolesGrid.Dock = 'Top'
$form.Controls.Add($UserRolesGrid)
$UserPropertiesGrid = New-Object System.Windows.Forms.GroupBox
$UserPropertiesGrid.Size=New-Object System.Drawing.Size($UserGrid.Size)
$UserPropertiesGrid.Visible = $false
$UserPropertiesGrid.Dock = 'Top'
$form.Controls.Add($UserPropertiesGrid)
$CopyButton = New-Object System.Windows.Forms.Label
$CopyButton.Location = New-Object System.Drawing.Size($((($UserGrid.Width-264)*3/4)-30),$($UserPropertiesGrid.Top +4))
$CopyButton.Size = New-Object System.Drawing.Size(20,20)
if (!(Test-Path variable:$copyImage)){
$CopyButton.Image = $copyImage
} else {
$CopyButton.Text = "C"
}
$CopyButton.Image = $copyImage
$CopyButton.Visible = $false
$CopyButton.Cursor = "Hand"
$CopyButton.Add_Click({
(Write-Output $UserProperties.SelectedRows[0].Cells['Value'].Value) | Set-Clipboard
$CopyButton.Visible = $false
})
$UserPropertiesGrid.Controls.Add($CopyButton)
$PasteButton = New-Object System.Windows.Forms.Label
$PasteButton.Location = New-Object System.Drawing.Size($($CopyButton.Right+4),$($UserPropertiesGrid.Top +4))
$PasteButton.Size = New-Object System.Drawing.Size(20,20)
$PasteButton.Image = $pasteImage
$PasteButton.Cursor = "Hand"
$PasteButton.Visible = $false
if (!(Test-Path variable:$pasteImage)){
$PasteButton.Image = $pasteImage
} else {
$PasteButton.Text = "P"
}
$PasteButton.Add_Click({
$UserProperties.SelectedRows[0].Cells['Value'].Value = Get-Clipboard
$PasteButton.Visible = $false
})
$UserPropertiesGrid.Controls.Add($PasteButton)
$GroupGrid = New-Object System.Windows.Forms.GroupBox
$GroupGrid.Size=New-Object System.Drawing.Size($UserGrid.Size)
$GroupGrid.Visible = $false
$GroupGrid.Dock = 'Top'
$form.Controls.Add($GroupGrid)
$BottomPanel = New-Object System.Windows.Forms.Panel
$BottomPanel.Location = New-Object System.Drawing.Size($($dgv.Right + 2),0)
$BottomPanel.Size = New-Object System.Drawing.Size(744, 29)
$BottomPanel.Dock = "Top"
$BottomPanel.BackColor = "Transparent"
$form.Controls.Add($BottomPanel)
$form_type = ""
if ($form_type -eq "test") {
$UsernameLabel = New-Object System.Windows.Forms.Button
$UsernameLabel.Location = New-Object System.Drawing.Size(0, 2)
$UsernameLabel.Size = New-Object System.Drawing.Size(55,25)
$UsernameLabel.Font = New-Object System.Drawing.Font("Calibri",10.5,[System.Drawing.FontStyle]::Regular)
$UsernameLabel.ForeColor = "Blue"
} else {
$UsernameLabel = New-Object System.Windows.Forms.Label
$UsernameLabel.Location = New-Object System.Drawing.Size(4,5)
$UsernameLabel.Size = New-Object System.Drawing.Size(50,24)
}
$UsernameLabel.Text = "User"
$UsernameLabel.FlatStyle = "Flat"
$UsernameLabel.BackColor = "Transparent"
$UsernameLabel.Add_Click({
if ($form_type -eq "test") {Switch-View}
})
$BottomPanel.Controls.Add($UsernameLabel)
$UsernameTextbox = New-Object System.Windows.Forms.TextBox
$UsernameTextbox.Location = New-Object System.Drawing.Size($UsernameLabel.Right,2)
$UsernameTextbox.Size = New-Object System.Drawing.Size($($UserGrid.Width/2-20-$UserNameLabel.Right),25)
$UsernameTextbox.Cursor = "Arrow"
$UsernameTextbox.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$UsernameTextbox.BackColor = "LightGray"
$UsernameTextbox.ReadOnly = $true
$UsernameTextbox.TextAlign = "center"
$UsernameTextbox.AllowDrop = $true
$UsernameTextbox.Add_TextChanged({
if ($BlockLabel.Text -ne "x") {
$CurrentRoles.Rows.Clear()
$BackupRoles.Rows.Clear()
Check-Components
} elseif ($UsernameTextbox.Text.Length -eq 0 -and $ResetRadioButton.Visible -eq $true) {Check-Components}
if ($UserRolesGrid.Visible -and $UsernameTextbox.Text.Length -gt 0) {Fetch-Roles}
})
$BottomPanel.Controls.Add($UsernameTextbox)
$GroupsTextbox = New-Object System.Windows.Forms.TextBox
$GroupsTextbox.Location = New-Object System.Drawing.Size($UsernameLabel.Right,2)
$GroupsTextbox.Size = New-Object System.Drawing.Size(450,$UsernameTextbox.Height)
$GroupsTextbox.Visible = $false