-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsAdminToolkit.ps1
More file actions
9085 lines (8091 loc) · 418 KB
/
Copy pathWindowsAdminToolkit.ps1
File metadata and controls
9085 lines (8091 loc) · 418 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
<#
.SYNOPSIS
Provides interactive and noninteractive tools for authorized Windows administration.
.DESCRIPTION
Windows Admin Toolkit 3.0.1 supports local administration and
bounded remote execution through PowerShell Remoting or PsExec. PowerShell
Remoting is the default because it does not place passwords on process
command lines. The optional PsExec transport uses only the current Windows
identity and requires a valid Microsoft signature on the executable.
The script is compatible with Windows PowerShell 5.1 and PowerShell 7.x on
Windows. It does not change WinRM, firewall, TrustedHosts, or execution-policy
settings automatically.
.PARAMETER Transport
Remote transport. WinRM is the secure default. PsExec is an explicit fallback.
.PARAMETER PsExecPath
Path or command name for a Microsoft-signed PsExec 2.43 or newer executable.
.PARAMETER WinRmIdentity
Optional in-memory PSCredential object for WinRM. Automation mode rejects
username strings so native parameter binding cannot open credential UI.
Credential remains a backward-compatible parameter alias.
PsExec deliberately uses only the current Windows identity to prevent
command-line password exposure.
.PARAMETER MaxConcurrentJobs
Maximum number of remote targets processed at one time.
.PARAMETER RetryCount
Retry count for read-only remote actions. State-changing actions are never
retried automatically.
.PARAMETER RetryDelaySeconds
Delay between retries of read-only remote actions.
.PARAMETER OperationTimeoutMinutes
Per-batch remote-operation timeout.
.PARAMETER ConnectivityTimeoutSeconds
Timeout for preflight connection checks.
.PARAMETER LogFile
Optional log path. The default is under the current user's local application
data folder.
.PARAMETER UseSsl
Uses WinRM over HTTPS.
.PARAMETER Authentication
WinRM authentication mechanism. Basic, CredSSP, and unencrypted modes are not
supported by this tool.
.PARAMETER Quiet
Suppresses routine log messages. Interactive menus and safety prompts remain.
.PARAMETER SkipConnectivityCheck
Skips the remote preflight check. The actual operation still enforces its
timeout and reports connection failures.
.PARAMETER Automation
Runs one named action without menus or prompts and returns a versioned JSON
result envelope.
.PARAMETER PolicyPath
Optional literal path to a versioned JSON policy profile. A supplied policy
can only narrow the toolkit's built-in permissions and safety limits.
.PARAMETER AuditPath
Optional literal path for a new per-run JSON Lines audit file. Existing
files are never appended to or overwritten.
.PARAMETER AuditEventLog
Also writes bounded audit records to the Windows Event Log. This integration
is off by default and requires an already-registered event source.
.PARAMETER AuditEventSource
Existing Windows Event Log source used with AuditEventLog. The toolkit never
creates or modifies event-source registration.
.PARAMETER PlanOperation
Controlled-orchestration operation: Create, Approve, Execute, or Resume.
.PARAMETER PlanPath
New plan path for Create, or an existing reviewed plan for later operations.
.PARAMETER ApprovedPlanPath
New immutable plan path written by Approve.
.PARAMETER CheckpointPath
New checkpoint path for Execute, or an existing checkpoint for Resume.
.PARAMETER ApprovedBy
Bounded reviewer identity recorded by Approve. It is metadata, not proof of
Windows identity or a digital signature.
.PARAMETER ApprovalReference
Bounded ticket, change, or review reference recorded by Approve.
.PARAMETER PlanApprovalText
Exact approval text containing the complete canonical plan hash.
.PARAMETER Action
Stable action identifier used by automation mode.
.PARAMETER ListActions
Returns the stable action catalog and input requirements without executing
an action.
.PARAMETER Preflight
Validates the complete automation request and discovers target capabilities
without executing the requested action.
.PARAMETER Local
Selects the local computer for automation mode.
.PARAMETER ComputerName
Selects one validated remote computer for automation mode.
.PARAMETER ComputerListPath
Selects a validated remote computer-list file for automation mode.
.PARAMETER JsonOutputPath
JSON result destination for automation mode. Use a single hyphen or STDOUT
for stdout. STDOUT is recommended with powershell.exe -File.
.PARAMETER ConfirmationText
Exact action-specific authorization text for an actual state-changing run.
.PARAMETER TargetListConfirmationText
Exact USE TARGET LIST authorization text required for more than 25 targets.
.PARAMETER PsExecConfirmationText
Exact USE PSEXEC authorization text required for the optional PsExec transport.
.PARAMETER TopCount
Maximum processes returned by the RunningProcesses automation action.
.PARAMETER IncludeKB
Optional KB identifiers for the WindowsUpdate automation action. An empty
array selects all applicable software updates.
.PARAMETER RebootDelaySeconds
Delay before the ScheduleReboot automation action requests a reboot.
.PARAMETER ServiceName
Validated service name for the ServiceManagement automation action.
.PARAMETER ServiceAction
Query, Start, Stop, or Restart for the ServiceManagement automation action.
.PARAMETER ProcessName
Exact process name for the TerminateProcess automation action.
.PARAMETER MinimumAgeDays
Minimum age of files eligible for the ClearTempFiles automation action.
.PARAMETER MaximumFiles
Maximum files examined by ClearTempFiles on each target.
.PARAMETER TaskPath
Validated scheduled-task path prefix for the ScheduledTasks automation action.
.PARAMETER MaximumTasks
Maximum scheduled tasks returned per target.
.PARAMETER EventLogName
Validated event-log channel for the EventLogQuery automation action.
.PARAMETER EntryCount
Maximum event-log entries returned per target.
.PARAMETER EventLevel
One or more event levels for the EventLogQuery automation action.
.PARAMETER RegistryPath
Validated registry provider or hive path for the RegistryRead automation action.
.PARAMETER RegistryValueName
Optional registry value name. An empty value lists all values.
.PARAMETER CommandText
Unsandboxed command text for the CustomCommand automation action.
.PARAMETER PowerShellText
Unsandboxed source text for the CustomPowerShell automation action.
.PARAMETER PowerShellFile
Literal local .ps1 path for the CustomPowerShell automation action.
.EXAMPLE
.\WindowsAdminToolkit.ps1
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Transport WinRM -UseSsl
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Transport PsExec -PsExecPath C:\Tools\PsExec64.exe
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Automation -Action SystemInfo -Local -JsonOutputPath -
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Automation -ListActions -JsonOutputPath -
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Automation -Action SystemInfo -Local -PolicyPath .\read-only-local.json -Preflight -JsonOutputPath -
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Automation -Action SystemInfo -Local -AuditPath C:\Audit\system-info.jsonl -JsonOutputPath C:\Results\system-info.json
.EXAMPLE
.\WindowsAdminToolkit.ps1 -Automation -PlanOperation Create -PlanPath C:\ChangePlans\system-info-pending.watplan.json -Action SystemInfo -Local -JsonOutputPath -
.NOTES
Version: 3.0.1
License: MIT
Use only on systems you own or are explicitly authorized to administer.
#>
#Requires -Version 5.1
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
[Parameter()]
[string]$Transport = 'WinRM',
[Parameter()]
[string]$PsExecPath = 'PsExec64.exe',
[Parameter()]
[AllowNull()]
[Alias('Credential')]
[object]$WinRmIdentity,
[Parameter()]
[int]$MaxConcurrentJobs = 8,
[Parameter()]
[int]$RetryCount = 1,
[Parameter()]
[int]$RetryDelaySeconds = 3,
[Parameter()]
[int]$OperationTimeoutMinutes = 30,
[Parameter()]
[int]$ConnectivityTimeoutSeconds = 5,
[Parameter()]
[string]$LogFile,
[Parameter()]
[switch]$UseSsl,
[Parameter()]
[string]$Authentication = 'Default',
[Parameter()]
[switch]$Quiet,
[Parameter()]
[switch]$SkipConnectivityCheck,
[Parameter()]
[switch]$Automation,
[Parameter()]
[AllowEmptyString()]
[string]$PolicyPath = '',
[Parameter()]
[AllowEmptyString()]
[string]$AuditPath = '',
[Parameter()]
[switch]$AuditEventLog,
[Parameter()]
[AllowEmptyString()]
[string]$AuditEventSource = 'WindowsAdminToolkit',
[Parameter()]
[AllowEmptyString()]
[string]$PlanOperation = '',
[Parameter()]
[AllowEmptyString()]
[string]$PlanPath = '',
[Parameter()]
[AllowEmptyString()]
[string]$ApprovedPlanPath = '',
[Parameter()]
[AllowEmptyString()]
[string]$CheckpointPath = '',
[Parameter()]
[AllowEmptyString()]
[string]$ApprovedBy = '',
[Parameter()]
[AllowEmptyString()]
[string]$ApprovalReference = '',
[Parameter()]
[AllowEmptyString()]
[string]$PlanApprovalText = '',
[Parameter()]
[AllowEmptyString()]
[string]$Action = '',
[Parameter()]
[switch]$ListActions,
[Parameter()]
[switch]$Preflight,
[Parameter()]
[switch]$Local,
[Parameter()]
[AllowEmptyString()]
[string]$ComputerName = '',
[Parameter()]
[AllowEmptyString()]
[string]$ComputerListPath = '',
[Parameter()]
[string]$JsonOutputPath = '-',
[Parameter()]
[AllowEmptyString()]
[string]$ConfirmationText = '',
[Parameter()]
[AllowEmptyString()]
[string]$TargetListConfirmationText = '',
[Parameter()]
[AllowEmptyString()]
[string]$PsExecConfirmationText = '',
[Parameter()]
[int]$TopCount = 20,
[Parameter()]
[string[]]$IncludeKB = @(),
[Parameter()]
[int]$RebootDelaySeconds = 60,
[Parameter()]
[AllowEmptyString()]
[string]$ServiceName = '',
[Parameter()]
[AllowEmptyString()]
[string]$ServiceAction = 'Query',
[Parameter()]
[AllowEmptyString()]
[string]$ProcessName = '',
[Parameter()]
[int]$MinimumAgeDays = 2,
[Parameter()]
[int]$MaximumFiles = 50000,
[Parameter()]
[AllowEmptyString()]
[string]$TaskPath = '\',
[Parameter()]
[int]$MaximumTasks = 50,
[Parameter()]
[AllowEmptyString()]
[string]$EventLogName = 'System',
[Parameter()]
[int]$EntryCount = 20,
[Parameter()]
[string[]]$EventLevel = @('Error', 'Warning'),
[Parameter()]
[AllowEmptyString()]
[string]$RegistryPath = '',
[Parameter()]
[AllowEmptyString()]
[string]$RegistryValueName = '',
[Parameter()]
[AllowEmptyString()]
[string]$CommandText = '',
[Parameter()]
[AllowEmptyString()]
[string]$PowerShellText = '',
[Parameter()]
[AllowEmptyString()]
[string]$PowerShellFile = ''
)
$Script:ToolkitVersion = '3.0.1'
$Script:WasDotSourced = $MyInvocation.InvocationName -eq '.'
$Script:ToolkitPath = $PSCommandPath
$Script:InvocationParameters = @{}
foreach ($boundName in $PSBoundParameters.Keys) {
$canonicalBoundName = if ($boundName -eq 'WinRmIdentity') { 'Credential' } else { $boundName }
$Script:InvocationParameters[$canonicalBoundName] = $PSBoundParameters[$boundName]
}
$normalizedTransport = if ($Transport -ieq 'WinRM') { 'WinRM' } elseif ($Transport -ieq 'PsExec') { 'PsExec' } else { $Transport }
$normalizedAuthentication = if ($Authentication -ieq 'Default') { 'Default' } elseif ($Authentication -ieq 'Kerberos') { 'Kerberos' } elseif ($Authentication -ieq 'Negotiate') { 'Negotiate' } else { $Authentication }
$Script:State = [ordered]@{
LogFile = $null
Quiet = [bool]$Quiet
Transport = $normalizedTransport
PsExecPath = $PsExecPath
PsExecFullPath = $null
Credential = $WinRmIdentity
MaxConcurrentJobs = $MaxConcurrentJobs
RetryCount = $RetryCount
RetryDelaySeconds = $RetryDelaySeconds
OperationTimeoutMinutes = $OperationTimeoutMinutes
ConnectivityTimeoutSeconds = $ConnectivityTimeoutSeconds
UseSsl = [bool]$UseSsl
Authentication = $normalizedAuthentication
SkipConnectivityCheck = [bool]$SkipConnectivityCheck
PolicyProfile = $null
AuditContext = $null
}
function Test-WindowsPlatform {
[CmdletBinding()]
param()
return $env:OS -eq 'Windows_NT'
}
function Test-AdminLiteralFilePathText {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$LiteralPath
)
if ([string]::IsNullOrWhiteSpace($LiteralPath) -or
$LiteralPath -match '[\x00-\x1F\x7F]' -or
$LiteralPath -match '(?i)^\\\\[.?]\\' -or
$LiteralPath -match '(?i)^\\\\[^\\]+\\(?:pipe|mailslot)(?:\\|$)' -or
[System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($LiteralPath)) {
return $false
}
$pathWithoutDrive = if ($LiteralPath -match '^[A-Za-z]:') { $LiteralPath.Substring(2) } else { $LiteralPath }
if ($pathWithoutDrive.Contains(':')) {
return $false
}
foreach ($segment in @($LiteralPath -split '[\\/]')) {
if ([string]::IsNullOrEmpty($segment) -or $segment -eq '.' -or $segment -match '^[A-Za-z]:$') {
continue
}
if ($segment -eq '..' -or $segment.Length -gt 255 -or $segment.TrimEnd(' ', '.') -cne $segment) {
return $false
}
if ($segment.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -ge 0) {
return $false
}
$deviceName = @($segment -split '\.', 2)[0].TrimEnd(' ', '.')
if ($deviceName -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$') {
return $false
}
}
return $true
}
function Read-AdminBoundedUtf8File {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$LiteralPath,
[Parameter()]
[ValidateRange(1, 16777216)]
[int]$MaximumBytes = 1048576
)
if (-not (Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
throw "Input file not found: $LiteralPath"
}
$stream = $null
try {
$stream = [System.IO.File]::Open($LiteralPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read)
$fileLength = $stream.Length
if ($fileLength -gt $MaximumBytes) {
throw "The input file exceeds the $MaximumBytes byte limit."
}
$bytes = New-Object 'byte[]' ([int]$fileLength)
$offset = 0
while ($offset -lt $bytes.Length) {
$readCount = $stream.Read($bytes, $offset, $bytes.Length - $offset)
if ($readCount -le 0) {
throw 'The input file ended before it could be read completely.'
}
$offset += $readCount
}
}
finally {
if ($stream) {
$stream.Dispose()
}
}
$textOffset = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
$textOffset = 3
}
try {
$strictUtf8 = New-Object System.Text.UTF8Encoding($false, $true)
return $strictUtf8.GetString($bytes, $textOffset, $bytes.Length - $textOffset)
}
catch [System.Text.DecoderFallbackException] {
throw 'The input file must contain valid UTF-8 text.'
}
}
function Get-AdminRuntimeConfigurationError {
[CmdletBinding()]
param()
if ($Script:State.Transport -notin @('WinRM', 'PsExec')) {
return "Unsupported transport: $($Script:State.Transport)"
}
if ($Script:State.Authentication -notin @('Default', 'Kerberos', 'Negotiate')) {
return "Unsupported WinRM authentication value: $($Script:State.Authentication)"
}
if ($Script:State.Transport -eq 'PsExec') {
foreach ($winRmOnlyParameter in @('Authentication', 'UseSsl')) {
if (Test-AdminParameterBound -Parameters $Script:InvocationParameters -Name $winRmOnlyParameter) {
return "Parameter -$winRmOnlyParameter is valid only with the WinRM transport."
}
}
}
elseif (Test-AdminParameterBound -Parameters $Script:InvocationParameters -Name 'PsExecPath') {
return 'Parameter -PsExecPath is valid only with the PsExec transport.'
}
if ($null -ne $Script:State.Credential -and $Script:State.Credential -isnot [System.Management.Automation.PSCredential]) {
return 'Credential must be supplied as an in-memory PSCredential object. Username strings are rejected in automation mode to prevent credential prompts.'
}
if ($Script:State.MaxConcurrentJobs -lt 1 -or $Script:State.MaxConcurrentJobs -gt 32) {
return 'MaxConcurrentJobs must be from 1 through 32.'
}
if ($Script:State.RetryCount -lt 0 -or $Script:State.RetryCount -gt 3) {
return 'RetryCount must be from 0 through 3.'
}
if ($Script:State.RetryDelaySeconds -lt 1 -or $Script:State.RetryDelaySeconds -gt 60) {
return 'RetryDelaySeconds must be from 1 through 60.'
}
if ($Script:State.OperationTimeoutMinutes -lt 1 -or $Script:State.OperationTimeoutMinutes -gt 180) {
return 'OperationTimeoutMinutes must be from 1 through 180.'
}
if ($Script:State.ConnectivityTimeoutSeconds -lt 1 -or $Script:State.ConnectivityTimeoutSeconds -gt 60) {
return 'ConnectivityTimeoutSeconds must be from 1 through 60.'
}
if ($Script:State.Transport -eq 'PsExec' -and $Script:State.Credential) {
return 'PsExec does not accept alternate credentials in this toolkit.'
}
return $null
}
function Initialize-AdminLog {
[CmdletBinding()]
param(
[Parameter()]
[string]$RequestedPath
)
if ([string]::IsNullOrWhiteSpace($RequestedPath)) {
$basePath = $env:LOCALAPPDATA
if ([string]::IsNullOrWhiteSpace($basePath)) {
$basePath = if ($PSScriptRoot) { $PSScriptRoot } else { (Get-Location).Path }
}
$logDirectory = Join-Path $basePath 'WindowsAdminToolkit\Logs'
$RequestedPath = Join-Path $logDirectory ("WindowsAdminToolkit_{0}_{1}.log" -f (Get-Date -Format 'yyyyMMdd_HHmmss_fff'), [guid]::NewGuid().ToString('N').Substring(0, 8))
}
if (-not (Test-AdminLiteralFilePathText -LiteralPath $RequestedPath)) {
throw 'The log path contains an unsafe or unsupported component.'
}
$fullPath = [System.IO.Path]::GetFullPath($RequestedPath)
$parent = Split-Path -Parent $fullPath
if ([string]::IsNullOrWhiteSpace($parent)) {
throw 'The log path must include a valid parent directory.'
}
if (-not (Test-Path -LiteralPath $parent -PathType Container)) {
[void][System.IO.Directory]::CreateDirectory($parent)
}
if (Test-Path -LiteralPath $fullPath -PathType Container) {
throw "The log path points to a directory: $fullPath"
}
$logProbe = $null
try {
$logProbe = [System.IO.File]::Open($fullPath, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Read)
}
finally {
if ($logProbe) {
$logProbe.Dispose()
}
}
$Script:State.LogFile = $fullPath
return $fullPath
}
function Write-AdminLog {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Message,
[Parameter()]
[ValidateSet('INFO', 'WARN', 'ERROR', 'SUCCESS', 'DEBUG')]
[string]$Level = 'INFO',
[Parameter()]
[switch]$NoConsole
)
$entry = '[{0}] [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
if (-not [string]::IsNullOrWhiteSpace([string]$Script:State.LogFile)) {
try {
$encoding = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::AppendAllText($Script:State.LogFile, $entry + [Environment]::NewLine, $encoding)
}
catch {
if (-not $NoConsole -and -not $Script:State.Quiet) {
Write-Warning "Unable to write to the log file: $($_.Exception.Message)"
}
}
}
if (-not $NoConsole -and -not $Script:State.Quiet) {
$color = switch ($Level) {
'ERROR' { 'Red' }
'WARN' { 'Yellow' }
'SUCCESS' { 'Green' }
'DEBUG' { 'DarkGray' }
default { 'Gray' }
}
Write-Host $entry -ForegroundColor $color
}
}
function Write-AdminBanner {
[CmdletBinding()]
param()
Write-Host ''
Write-Host '=====================================================================' -ForegroundColor Cyan
Write-Host " WINDOWS ADMIN TOOLKIT v$Script:ToolkitVersion" -ForegroundColor Cyan
Write-Host ' Authorized Windows administration with guarded remote execution' -ForegroundColor White
Write-Host '=====================================================================' -ForegroundColor Cyan
Write-Host ''
}
function Test-Administrator {
[CmdletBinding()]
param()
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
catch {
return $false
}
}
function Test-AdminHostname {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ComputerName
)
if ([string]::IsNullOrWhiteSpace($ComputerName)) {
return $false
}
$value = $ComputerName.Trim()
if ($value.Length -gt 253) {
return $false
}
$ip = $null
if ([System.Net.IPAddress]::TryParse($value, [ref]$ip)) {
return $ip.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork -and $ip.ToString() -ceq $value
}
if ($value.EndsWith('.')) {
$value = $value.Substring(0, $value.Length - 1)
}
if ([string]::IsNullOrWhiteSpace($value)) {
return $false
}
foreach ($label in $value.Split('.')) {
if ($label.Length -lt 1 -or $label.Length -gt 63) {
return $false
}
if ($label -notmatch '^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$') {
return $false
}
}
return $true
}
function Test-AdminLocalComputerName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ComputerName
)
if ([string]::IsNullOrWhiteSpace($ComputerName)) {
return $false
}
$value = $ComputerName.Trim()
if ($value.Length -gt 253 -or $value -match '\s') {
return $false
}
return $value.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -lt 0
}
function Import-AdminComputerList {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$LiteralPath,
[Parameter()]
[ValidateRange(1, 1000)]
[int]$MaximumTargets = 500
)
if (-not (Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
throw "Computer list not found: $LiteralPath"
}
$rawText = Read-AdminBoundedUtf8File -LiteralPath $LiteralPath -MaximumBytes 1048576
$rawLines = @($rawText -split '\r\n|\n|\r')
$valid = New-Object 'System.Collections.Generic.List[string]'
$invalidLines = New-Object 'System.Collections.Generic.List[int]'
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
for ($index = 0; $index -lt $rawLines.Count; $index++) {
$value = [string]$rawLines[$index]
if ([string]::IsNullOrWhiteSpace($value) -or $value.TrimStart().StartsWith('#')) {
continue
}
$value = $value.Trim()
if (-not (Test-AdminHostname -ComputerName $value)) {
$invalidLines.Add($index + 1) | Out-Null
continue
}
if ($seen.Add($value)) {
$valid.Add($value) | Out-Null
}
if ($valid.Count -gt $MaximumTargets) {
throw "The list exceeds the maximum of $MaximumTargets unique targets."
}
}
return [pscustomobject]@{
Computers = $valid.ToArray()
InvalidLines = $invalidLines.ToArray()
}
}
function Test-AdminServiceName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ServiceName
)
if ([string]::IsNullOrWhiteSpace($ServiceName) -or $ServiceName.Length -gt 256) {
return $false
}
return $ServiceName -match '^[A-Za-z0-9_.-]+$'
}
function Test-AdminProcessName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ProcessName
)
if ([string]::IsNullOrWhiteSpace($ProcessName) -or $ProcessName.Length -gt 128) {
return $false
}
return $ProcessName -match '^[A-Za-z0-9_.-]+$'
}
function Test-AdminRegistryPath {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$RegistryPath
)
if ([string]::IsNullOrWhiteSpace($RegistryPath) -or $RegistryPath.Length -gt 2048) {
return $false
}
$value = $RegistryPath.Trim()
if ($value.IndexOf([char]0) -ge 0 -or $value -match '[\r\n]') {
return $false
}
return $value -match '^(?i)(?:(?:HKLM|HKCU|HKCR|HKU|HKCC):(?:\\[^\r\n]*)?|(?:HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG)(?:\\[^\r\n]*)?)$' -and
$value -notmatch '(?:^|\\)\.\.(?:\\|$)'
}
function Test-AdminRegistryValueName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ValueName
)
return $ValueName.Length -le 16383 -and $ValueName.IndexOf([char]0) -lt 0 -and $ValueName -notmatch '[\r\n]'
}
function Test-AdminEventLogName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$LogName
)
if ([string]::IsNullOrWhiteSpace($LogName) -or $LogName.Length -gt 256) {
return $false
}
return $LogName -match '^[A-Za-z0-9][A-Za-z0-9 ._\-/]*$' -and $LogName -notmatch '\.\.'
}
function Test-AdminTaskPath {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$TaskPath
)
if ([string]::IsNullOrWhiteSpace($TaskPath) -or $TaskPath.Length -gt 512) {
return $false
}
return $TaskPath -match '^\\(?:[A-Za-z0-9 ._-]+\\)*$' -and $TaskPath -notmatch '\.\.'
}
function Test-AdminKbNumber {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$KbNumber
)
return $KbNumber.Trim().ToUpperInvariant() -match '^KB\d{4,8}$'
}
function Test-AdminPowerShellText {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$ScriptText
)
if ([string]::IsNullOrWhiteSpace($ScriptText) -or $ScriptText.Length -gt 1048576) {
return [pscustomobject]@{
IsValid = $false
Errors = @('The script is empty or exceeds the 1 MiB limit.')
}
}
$tokens = $null
$errors = $null
[void][System.Management.Automation.Language.Parser]::ParseInput($ScriptText, [ref]$tokens, [ref]$errors)
return [pscustomobject]@{
IsValid = @($errors).Count -eq 0
Errors = @($errors | ForEach-Object { $_.Message })
}
}
function ConvertTo-AdminCsvSafeValue {
[CmdletBinding()]
param(
[Parameter()]
[AllowNull()]
$Value
)
if ($null -eq $Value) {
return $null
}
if ($Value -is [array]) {
$text = $Value -join '; '
}
elseif ($Value -is [System.Collections.IDictionary] -or $Value -is [pscustomobject]) {
$text = $Value | ConvertTo-Json -Compress -Depth 8
}
else {
$text = [string]$Value
}
if ($text -match '^[\s\t\r\n]*[=+\-@]') {
return "'$text"
}
return $text
}
function ConvertTo-AdminFlatObject {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowNull()]
$InputObject
)
$flat = [ordered]@{}
if ($InputObject -is [System.Collections.IDictionary]) {
foreach ($key in $InputObject.Keys) {
$flat[[string]$key] = ConvertTo-AdminCsvSafeValue -Value $InputObject[$key]
}
}
else {
foreach ($property in $InputObject.PSObject.Properties) {
if ($property.Name -in @('PSComputerName', 'RunspaceId', 'PSShowComputerName')) {
continue
}
$flat[$property.Name] = ConvertTo-AdminCsvSafeValue -Value $property.Value
}
}
return [pscustomobject]$flat
}
function ConvertTo-AdminHtmlEncoded {
[CmdletBinding()]