Repository navigation
Expand file tree
/
Copy pathBootScope.ps1
More file actions
3493 lines (3221 loc) · 182 KB
/
Copy pathBootScope.ps1
File metadata and controls
3493 lines (3221 loc) · 182 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
#Requires -Version 5.1
<#
启视 BootScope
https://github.com/<你的账号>/bootscope
Windows 自启动项 增 / 删 / 改 / 查 工具
覆盖位置:
· 注册表 Run / RunOnce HKCU · HKLM · WOW6432Node · HKU\S-1-5-18 · HKU\.DEFAULT
· 启动文件夹 当前用户 · 所有用户
· 计划任务 登录 / 开机触发
· 服务 自动启动
启用 / 禁用采用 Windows 原生 StartupApproved 机制,与任务管理器完全一致。
所有删除操作先写入回滚日志,支持撤销。
#>
param(
# 提权/STA 重启时由自己传入,防止提权始终失败时无限弹 UAC
[switch]$Relaunched
)
# ══════════════════════════════════════════════════════════════════
# 0. 自提权 + 隐藏控制台
# ══════════════════════════════════════════════════════════════════
$ErrorActionPreference = 'Stop'
function Test-Admin {
([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
$isAdmin = Test-Admin
$isSta = ([Threading.Thread]::CurrentThread.GetApartmentState() -eq 'STA')
# WPF 要求 STA 单线程单元;pwsh 7 在某些宿主下默认 MTA,需带 -STA 重启。
if (-not $isAdmin -or -not $isSta) {
Add-Type -AssemblyName System.Windows.Forms
# 已经重启过一次还是不满足条件,说明重启这条路走不通(组策略拦截、
# STA 检测异常等)。再启动一次只会无限弹 UAC,直接报错退出。
if ($Relaunched) {
[System.Windows.Forms.MessageBox]::Show(
"重新启动后仍未取得所需环境,已停止重试。`n`n管理员权限:$isAdmin`nSTA 单线程单元:$isSta`n`n" +
"请手动运行:`npwsh -NoProfile -STA -ExecutionPolicy Bypass -File `"<脚本路径>`"",
'启视 BootScope', 'OK', 'Error') | Out-Null
exit 1
}
$self = $PSCommandPath
if (-not $self) { $self = $MyInvocation.MyCommand.Definition }
$pwsh7 = 'C:\Program Files\PowerShell\7\pwsh.exe'
# 不能用 $env:WINDIR —— 它可由 HKCU\Environment 覆盖,而下面紧接着就是
# Start-Process -Verb RunAs,等于把攻击者指定的 exe 直接提权运行
# (经典 windir UAC bypass)。SystemDirectory 由系统解析,不受用户环境影响。
$ps51 = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell\v1.0\powershell.exe'
$exe = if (Test-Path $pwsh7) { $pwsh7 } else { $ps51 }
$argv = @('-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden',
'-File', "`"$self`"", '-Relaunched')
try {
if ($isAdmin) { Start-Process -FilePath $exe -ArgumentList $argv } # 仅缺 STA
else { Start-Process -FilePath $exe -ArgumentList $argv -Verb RunAs }
} catch {
[System.Windows.Forms.MessageBox]::Show(
"本工具需要管理员权限才能修改系统自启动项。`n`n提权请求被取消或失败:`n$($_.Exception.Message)",
'启视 BootScope', 'OK', 'Warning') | Out-Null
}
exit
}
try {
Add-Type -Namespace Native -Name Win -MemberDefinition @'
[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
'@
[Native.Win]::ShowWindow([Native.Win]::GetConsoleWindow(), 0) | Out-Null
} catch { }
Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase, System.Xaml, System.Windows.Forms
# ══════════════════════════════════════════════════════════════════
# 1. 常量与状态
# ══════════════════════════════════════════════════════════════════
$script:AppDir = Join-Path $env:LOCALAPPDATA 'BootScope'
$script:Journal = Join-Path $script:AppDir 'rollback.json'
# 更名前叫 StartupManager。老目录里有回滚日志、AI 配置、被改成手动的服务清单,
# 不搬过来这些全都读不到 —— 只在新目录尚不存在时搬一次,之后互不干扰。
$legacyDir = Join-Path $env:LOCALAPPDATA 'StartupManager'
if (-not (Test-Path $script:AppDir) -and (Test-Path $legacyDir)) {
try { Move-Item -LiteralPath $legacyDir -Destination $script:AppDir -Force -ErrorAction Stop } catch { }
}
if (-not (Test-Path $script:AppDir)) { New-Item -ItemType Directory -Path $script:AppDir -Force | Out-Null }
# 导出要带 BOM,否则 Excel 按 ANSI 解码、中文全乱码。但两代 PowerShell 的写法不同:
# PS7 的 'UTF8' 是无 BOM,要写 'utf8BOM';5.1 没有 utf8BOM 这个值,它的 'UTF8' 本来就带 BOM。
$script:ENC_BOM = if ($PSVersionTable.PSVersion.Major -ge 6) { 'utf8BOM' } else { 'UTF8' }
# 5.1 默认还在用 TLS 1.0/1.1,直连 api.anthropic.com 会握手失败
if ($PSVersionTable.PSVersion.Major -lt 6) {
try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch { }
}
$script:SigCache = @{}
$script:Items = @() # 全量条目
$script:View = @() # 当前筛选后、绑定到表格的条目
$script:VerifySig = $true
$script:LoadErrors = @() # 本次枚举中读取失败的位置,显示在统计条上
$script:JournalWarning = $null
# 被本工具从「自动」改成「手动」的服务。服务枚举默认只看 StartMode='Auto',
# 禁用后条目就会从列表里蒸发、再也无法在界面里重新启用;记下来才能继续显示。
$script:SvcStateFile = Join-Path $script:AppDir 'managed-services.json'
function Get-ManagedServices {
if (-not (Test-Path $script:SvcStateFile)) { return @() }
try { return ,@(Get-Content $script:SvcStateFile -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { return ,@() }
}
function Set-ManagedService {
param([string]$Name, [bool]$Tracked)
$cur = [System.Collections.Generic.List[string]]@(Get-ManagedServices | Where-Object { $_ })
$hit = @($cur | Where-Object { $_ -ieq $Name })
if ($Tracked -and $hit.Count -eq 0) { $cur.Add($Name) }
elseif (-not $Tracked -and $hit.Count -gt 0) {
$keep = @($cur | Where-Object { $_ -inotmatch "^$([regex]::Escape($Name))$" })
$cur = [System.Collections.Generic.List[string]]$keep
} else { return }
try { ($cur | ConvertTo-Json -Depth 2) | Set-Content $script:SvcStateFile -Encoding UTF8 } catch { }
}
$RUN_LOCS = @(
@{ Scope='HKCU'; Reg='HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Ap='HKCU'; ApSub='Run'; Label='HKCU\Run' }
@{ Scope='HKCU-Once'; Reg='HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'; Ap=$null; ApSub=$null; Label='HKCU\RunOnce' }
@{ Scope='HKCU32'; Reg='HKCU:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; Ap='HKCU'; ApSub='Run32'; Label='HKCU\WOW64\Run' }
@{ Scope='HKLM'; Reg='HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Ap='HKLM'; ApSub='Run'; Label='HKLM\Run' }
@{ Scope='HKLM-Once'; Reg='HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'; Ap=$null; ApSub=$null; Label='HKLM\RunOnce' }
@{ Scope='HKLM32'; Reg='HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; Ap='HKLM'; ApSub='Run32'; Label='HKLM\WOW64\Run' }
@{ Scope='HKLM32-Once';Reg='HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce'; Ap=$null; ApSub=$null; Label='HKLM\WOW64\RunOnce' }
@{ Scope='SYSTEM'; Reg='Registry::HKEY_USERS\S-1-5-18\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Ap=$null; ApSub=$null; Label='SYSTEM账户\Run' }
@{ Scope='DEFAULT'; Reg='Registry::HKEY_USERS\.DEFAULT\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Ap=$null; ApSub=$null; Label='默认用户模板\Run' }
)
$FOLDER_LOCS = @(
@{ Scope='User'; Path=[Environment]::GetFolderPath('Startup'); Ap='HKCU'; Label='启动文件夹(当前用户)' }
@{ Scope='Common'; Path=[Environment]::GetFolderPath('CommonStartup'); Ap='HKLM'; Label='启动文件夹(所有用户)' }
)
# ══════════════════════════════════════════════════════════════════
# 2. 工具函数
# ══════════════════════════════════════════════════════════════════
function Resolve-Target {
param([string]$Cmd)
if ([string]::IsNullOrWhiteSpace($Cmd)) { return @{ Path=''; Args='' } }
$c = $Cmd.Trim()
if ($c.StartsWith('"')) {
$i = $c.IndexOf('"', 1)
if ($i -gt 0) { return @{ Path=$c.Substring(1, $i-1); Args=$c.Substring($i+1).Trim() } }
}
$m = [regex]::Match($c, '^(.*?\.(?:exe|com|bat|cmd|vbs|vbe|js|ps1|scr|dll))(?:\s|,|$)', 'IgnoreCase')
if ($m.Success) { return @{ Path=$m.Groups[1].Value; Args=$c.Substring($m.Groups[1].Value.Length).Trim() } }
$sp = $c.IndexOf(' ')
if ($sp -gt 0) { return @{ Path=$c.Substring(0, $sp); Args=$c.Substring($sp+1) } }
return @{ Path=$c; Args='' }
}
function Expand-Path { param([string]$P) if ($P) { [Environment]::ExpandEnvironmentVariables($P) } else { '' } }
# 判定目标文件是否存在。必须区分「确实缺失」与「无权读取」——
# 有些服务把自己装在 ProgramData 下并对普通用户设了 deny ACE,这类目录会让
# Test-Path 抛 Access denied;若当成缺失,就会把正在运行的服务误报为失效残留。
# 同时把裸文件名(powershell.exe)按 PATH 解析成完整路径。
function Resolve-ExistState {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return @{ State='na'; Path='' } }
$p = $Path.Trim('"')
if ($p -notmatch '[\\/]') {
try {
$c = @(Get-Command $p -CommandType Application -ErrorAction Stop)[0]
if ($c) { $p = $c.Source }
} catch { return @{ State='no'; Path=$Path } }
}
try {
if (Test-Path -LiteralPath $p -PathType Leaf -ErrorAction Stop) { return @{ State='yes'; Path=$p } }
return @{ State='no'; Path=$p }
} catch {
if ($_.Exception -is [System.UnauthorizedAccessException] -or
$_.Exception.Message -match 'denied|拒绝访问') { return @{ State='denied'; Path=$p } }
return @{ State='no'; Path=$p }
}
}
function Get-Sig {
param([string]$Path)
if (-not $script:VerifySig) { return @{ Status='未校验'; Signer='' } }
if ([string]::IsNullOrWhiteSpace($Path)) { return @{ Status='—'; Signer='' } }
$k = $Path.ToLower()
if ($script:SigCache.ContainsKey($k)) { return $script:SigCache[$k] }
$r = @{ Status='—'; Signer='' }
try {
if (Test-Path -LiteralPath $Path -PathType Leaf) {
$s = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
$r.Status = [string]$s.Status
if ($s.SignerCertificate) {
$cn = $s.SignerCertificate.Subject -replace '^CN=("?)([^",]+)\1.*', '$2'
$r.Signer = $cn.Trim()
}
}
} catch { $r.Status = '校验失败' }
$script:SigCache[$k] = $r
return $r
}
function Get-ApprovedState {
param([string]$Hive, [string]$Sub, [string]$Name)
if (-not $Hive) { return $true }
$p = "${Hive}:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\$Sub"
try {
if (Test-Path $p) {
$k = Get-Item $p
if ($k.GetValueNames() -contains $Name) {
$b = $k.GetValue($Name)
# 首字节偶数 = 启用,奇数 = 禁用(Windows 原生约定)
return (($b[0] -band 1) -eq 0)
}
}
} catch { }
return $true # 无记录 => 默认启用
}
function Set-ApprovedState {
param([string]$Hive, [string]$Sub, [string]$Name, [bool]$Enabled)
$p = "${Hive}:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\$Sub"
if (-not (Test-Path $p)) { New-Item -Path $p -Force | Out-Null }
if ($Enabled) {
$bytes = [byte[]]@(2,0,0,0, 0,0,0,0, 0,0,0,0)
} else {
$ft = [BitConverter]::GetBytes([DateTime]::Now.ToFileTime())
$bytes = [byte[]]@(3,0,0,0) + $ft
}
Set-ItemProperty -Path $p -Name $Name -Value $bytes -Type Binary -Force
}
# Remove-ItemProperty 的 -Name 走通配符匹配,这在删除注册表启动项时有两个后果:
# · 名为「*」的值(恶意软件会这么干)会连带删光整个 Run 键,而回滚日志只记了一条
# · 名含「[ ]」的值(Adobe ARM [Startup] 之类真实存在的名字)匹配不到,
# 删除静默失败但返回成功,界面报「已删除」而条目还在
# 所有删除路径一律走这里。注意 Set-ItemProperty -Name 反而是字面量语义,不能转义。
function Remove-RegValue {
param([string]$Path, [string]$Name, [switch]$Quiet)
$esc = [Management.Automation.WildcardPattern]::Escape($Name)
if ($Quiet) { Remove-ItemProperty -Path $Path -Name $esc -Force -ErrorAction SilentlyContinue }
else { Remove-ItemProperty -Path $Path -Name $esc -Force }
}
# StartupApproved 键路径在删除/编辑/恢复多处重复拼接,收敛到一处
function Get-ApprovedKeyPath {
param([string]$Hive, [string]$Sub)
if (-not $Hive) { return $null }
"${Hive}:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\$Sub"
}
# 回滚日志是 %LOCALAPPDATA% 下的普通 JSON 文件,同一用户的中完整性进程可以改写它。
# 而「撤销」会以管理员身份把记录里的 Loc / Extra.File 原样写回系统 —— 若不校验,
# 一个被篡改的日志就能让用户点一次撤销就往 HKLM\Services 或全局启动文件夹里写东西。
# 因此恢复前必须确认目标确实是本工具自己枚举的那些位置。
function Assert-JournalTarget {
param($r)
if ([string]$r.Kind -eq 'Task') {
# 计划任务不落在注册表/文件白名单里,单独校验:必须有名字,且不能指向系统任务树
if ([string]::IsNullOrWhiteSpace([string]$r.Extra.TaskName)) { throw '回滚记录缺少任务名,已拒绝恢复' }
if ([string]$r.Extra.TaskPath -like '\Microsoft\Windows\*') { throw '回滚记录指向系统计划任务,已拒绝恢复' }
return
}
switch ([string]$r.Kind) {
'Run' {
if ($RUN_LOCS.Reg -notcontains [string]$r.Loc) {
throw "回滚记录指向的注册表位置不在本工具管理范围内,已拒绝恢复:$($r.Loc)"
}
}
'Folder' {
$f = [string]$r.Extra.File
if (-not $f) { throw '回滚记录缺少文件路径,已拒绝恢复' }
$dir = $null
try { $dir = [IO.Path]::GetFullPath([IO.Path]::GetDirectoryName($f)).TrimEnd('\') } catch { }
if (-not $dir) { throw "回滚记录的文件路径无法解析,已拒绝恢复:$f" }
$ok = $false
foreach ($L in $FOLDER_LOCS) {
if (-not $L.Path) { continue }
$known = $null
try { $known = [IO.Path]::GetFullPath($L.Path).TrimEnd('\') } catch { continue }
if ($known -and $dir.Equals($known, [StringComparison]::OrdinalIgnoreCase)) { $ok = $true; break }
}
if (-not $ok) { throw "回滚记录指向的目录不是启动文件夹,已拒绝恢复:$f" }
}
default { throw "回滚记录的类型无法自动恢复:$($r.Kind)" }
}
if ([string]::IsNullOrWhiteSpace([string]$r.Name)) { throw '回滚记录缺少条目名称,已拒绝恢复' }
}
function Get-RiskInfo {
param([string]$Target, [string]$SigStatus, [string]$ExistState, [string]$Name, [string]$Kind, [string]$Cmd)
$notes = New-Object System.Collections.Generic.List[string]
$lvl = 'normal'
# 「文件不存在」以前会在这里直接 return,跳过后面全部规则。后果是
# rundll32 xxx.dll,Start 这类命令被 Resolve-Target 解析出一个不存在的路径后,
# 一个活着的持久化被标成「无害残留」,还会被「所有残留项」一键勾选。
# 现在改成:先记下残留,继续跑完所有规则,最后取较严重的那个等级。
$stale = ($ExistState -eq 'no')
if ($stale) { $notes.Add('目标文件不存在 —— 可能是失效残留,也可能是命令行未被正确解析,删除前请核对完整命令') }
if ($ExistState -eq 'denied') { $notes.Add('所在目录受 ACL 保护,未能读取该文件(不代表缺失)') }
$t = if ($Target) { $Target.ToLowerInvariant() } else { '' }
$ext = try { [IO.Path]::GetExtension($t) } catch { '' }
$isScript = $ext -in @('.vbs','.vbe','.bat','.cmd','.ps1','.js','.jse','.wsf')
$isBinary = $ext -in @('.exe','.dll','.com','.scr')
# 三态而非两态:'Valid' 才是真的验过;未校验 / 无权读取只是「不知道」,
# 以前把它们和 Valid 一起当成「签名没问题」,等于给关掉签名校验或设了
# deny-read ACL 的样本发免检通行证。
$sigKnownBad = ($SigStatus -notin @('Valid','未校验','—','校验失败'))
$sigUnknown = ($SigStatus -in @('未校验','—','校验失败')) -or ($ExistState -eq 'denied')
$bad = $sigKnownBad -or $sigUnknown
# 启动文件夹的物理路径本身就在 AppData\Roaming\Microsoft\Windows\… 之下,
# 不能算「伪装成微软目录」。
$inStartupFolder = ($t -match '\\start menu\\programs\\startup\\')
if ($isScript) {
$lvl = 'warning'
$notes.Add('脚本文件(无数字签名属正常)—— 实际风险取决于脚本内容,请确认来源')
} elseif ($sigKnownBad) {
$lvl = 'warning'; $notes.Add("数字签名:$SigStatus")
} elseif ($sigUnknown -and $ExistState -ne 'na') {
$notes.Add($(if ($SigStatus -eq '未校验') { '未校验数字签名(已在界面关闭校验)' } else { "未能校验数字签名:$SigStatus" }))
}
# 解释器 + 脚本参数:真正决定行为的是脚本,不是解释器本身
if ($t -match '\\(powershell|pwsh|cmd|wscript|cscript|mshta|rundll32|regsvr32)\.exe$') {
if ($lvl -eq 'normal') { $lvl = 'warning' }
# 先匹配带引号的路径(脚本路径常含空格),失败再退回无引号匹配
$sm = [regex]::Match($Cmd, '"([^"]+\.(?:ps1|vbs|vbe|bat|cmd|js|wsf|dll|scr))"', 'IgnoreCase')
if (-not $sm.Success) { $sm = [regex]::Match($Cmd, '([^\s",]+\.(?:ps1|vbs|vbe|bat|cmd|js|wsf|dll|scr))', 'IgnoreCase') }
if ($sm.Success) { $notes.Add("经系统解释器执行脚本:$($sm.Groups[1].Value) —— 实际行为由该脚本决定") }
else { $notes.Add('通过系统解释器启动 —— 请核对完整命令行') }
}
if ($isBinary -and $bad -and -not $inStartupFolder -and $t -match '\\appdata\\(roaming|local)\\microsoft\\') {
# 签名确实无效 → 危险;只是没验成 → 关注(提示用户去开校验),不静默放行
if ($sigKnownBad) { $lvl = 'critical'; $notes.Add('位于微软目录内却无有效签名 —— 典型的名称伪装手法') }
elseif ($lvl -ne 'critical') { $lvl = 'warning'; $notes.Add('位于微软目录内且签名未经确认 —— 建议开启签名校验后复查') }
}
if ($t -match '^[a-z]:\\users\\public\\') {
if ($lvl -eq 'normal') { $lvl = 'warning' }
$notes.Add('位于所有用户可写目录,任何低权限进程都能替换该文件')
}
if ($t -match '\\(temp|tmp)\\' -or $t -match '\\windows\\temp\\') {
$lvl = 'critical'; $notes.Add('位于临时目录 —— 正规软件不会从这里自启动')
}
if ($isBinary -and $bad -and $t -match '\\programdata\\') {
if ($lvl -eq 'normal') { $lvl = 'warning' }
$notes.Add('ProgramData 默认允许普通用户写入')
}
if ($Name -match '^(svchost|rundll32|csrss|lsass|explorer|winlogon|services|taskhost)(\.exe)?$' -and
$t -notmatch '\\windows\\(system32|syswow64)\\') {
$lvl = 'critical'; $notes.Add('使用系统进程名但不在 System32 —— 高度可疑')
}
# 残留只在没有更严重发现时才作为最终等级;critical / warning 优先级都高于 stale
if ($stale -and $lvl -eq 'normal') { $lvl = 'stale' }
if ($notes.Count -eq 0) {
$notes.Add($(if ($sigUnknown) { '路径正常;签名未经校验' } else { '签名有效,路径正常' }))
}
return @{ Level=$lvl; Note=($notes -join ';') }
}
# ── 条目类型 ──────────────────────────────────────────────────────
# 签名校验是刷新耗时的大头,所以分两趟:先不校验把列表铺出来,再后台逐个填。
# 第二趟要在条目已经绑在表格上之后改它的「签名 / 签署者 / 风险」——
# PSCustomObject 不实现 INotifyPropertyChanged,改了界面不会动,只能整表重绑,
# 那会丢掉滚动位置和选中行。所以条目改用一个实现了变更通知的真类型。
# 顺带也解决了原先「程序化改 Sel 后必须重绑 ItemsSource」的老问题。
$script:HasInpc = $false
try {
Add-Type -TypeDefinition @'
using System.ComponentModel;
public class SmItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void P(string n) { var h = PropertyChanged; if (h != null) h(this, new PropertyChangedEventArgs(n)); }
// 枚举完就不再变的字段
public string Name { get; set; }
public string Command { get; set; }
public string Target { get; set; }
public string Arguments { get; set; }
public string Kind { get; set; }
public string Scope { get; set; }
public string Label { get; set; }
public string Loc { get; set; }
public bool Enabled { get; set; }
public string StateText { get; set; }
public bool CanToggle { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool Exists { get; set; }
public string ExistState { get; set; } // yes / no / denied / na,重算风险时要用
public string ExistText { get; set; }
public object Extra { get; set; }
// 界面存活期间会被改动的字段,必须发通知
private bool _sel;
public bool Sel { get { return _sel; } set { if (_sel != value) { _sel = value; P("Sel"); } } }
private string _signer = "";
public string Signer { get { return _signer; } set { _signer = value; P("Signer"); } }
private string _sigStatus = "";
public string SigStatus { get { return _sigStatus; } set { _sigStatus = value; P("SigStatus"); } }
private string _sigText = "";
public string SigText { get { return _sigText; } set { _sigText = value; P("SigText"); } }
private string _risk = "normal";
public string Risk { get { return _risk; } set { _risk = value; P("Risk"); } }
private string _riskText = "";
public string RiskText { get { return _riskText; } set { _riskText = value; P("RiskText"); } }
private string _riskCell = "";
public string RiskCell { get { return _riskCell; } set { _riskCell = value; P("RiskCell"); } }
private int _riskRank = 3;
public int RiskRank { get { return _riskRank; } set { _riskRank = value; P("RiskRank"); } }
private string _riskNote = "";
public string RiskNote { get { return _riskNote; } set { _riskNote = value; P("RiskNote"); } }
private string _aiVerdict = "";
public string AiVerdict { get { return _aiVerdict; } set { _aiVerdict = value; P("AiVerdict"); } }
private object _aiReport;
public object AiReport { get { return _aiReport; } set { _aiReport = value; P("AiReport"); } }
}
'@ -ReferencedAssemblies @(
[System.ComponentModel.INotifyPropertyChanged].Assembly.Location,
[object].Assembly.Location
)
$script:HasInpc = $true
} catch {
# 编译不出来也能跑,只是退回「一趟到底」的旧行为,没有渐进填充
$script:HasInpc = $false
}
$RISK_TEXT = @{ critical='危险'; warning='关注'; stale='残留'; normal='正常' }
$RISK_RANK = @{ critical=0; warning=1; stale=2; normal=3 }
# 四种风险的行底色在浅色主题下亮度差不到 3%,实际几乎分辨不出,
# 且选中行的背景会把它整个盖掉。加一个字形前缀,让风险不依赖颜色也能读出来。
$RISK_GLYPH = @{ critical='⛔'; warning='⚠'; stale='○'; normal='✓' }
# 签名状态原本直接显示 .NET 的英文枚举(NotSigned / HashMismatch / …),
# 是整个中文界面里唯一的英文,且非技术用户看不懂。
$SIG_TEXT = @{
'Valid' = '有效'
'NotSigned' = '无签名'
'HashMismatch' = '哈希不符'
'NotTrusted' = '不受信任'
'UnknownError' = '未知错误'
'NotSupportedFileFormat' = '不支持的格式'
'Incompatible' = '不兼容'
}
function Get-SigText {
param([string]$Status)
if ([string]::IsNullOrEmpty($Status)) { return '' }
if ($SIG_TEXT.ContainsKey($Status)) { return $SIG_TEXT[$Status] }
return $Status # 未校验 / — / 校验失败 本来就是中文
}
function New-Item2 {
param($Name,$Cmd,$Kind,$Scope,$Label,$Loc,$Enabled,$CanToggle,$CanEdit,$CanDelete,$Extra)
$rt = Resolve-Target $Cmd
$es = Resolve-ExistState (Expand-Path $rt.Path)
# Resolve-Target 的非贪婪正则会把「rundll32 evil.dll,Start」整段当成路径
# (`.*?\.dll` 跨过了空格),解析出的路径当然不存在,于是一个活着的持久化
# 被判成失效残留。解析结果不存在且含空格时,退回只取第一个词再试一次。
if ($es.State -eq 'no' -and $rt.Path -match '\s') {
$first = ($rt.Path -split '\s+')[0]
if ($first) {
$es2 = Resolve-ExistState (Expand-Path $first)
if ($es2.State -ne 'no') {
$es = $es2
$rt = @{ Path=$first; Args=$Cmd.Substring([Math]::Min($Cmd.Length, $Cmd.IndexOf($first) + $first.Length)).Trim() }
}
}
}
$tp = $es.Path # 可能已由 PATH 解析成完整路径
$ex = ($es.State -eq 'yes')
$sg = if ($es.State -eq 'yes') { Get-Sig $tp } else { @{ Status='—'; Signer='' } }
$rk = Get-RiskInfo -Target $tp -SigStatus $sg.Status -ExistState $es.State -Name $Name -Kind $Kind -Cmd $Cmd
$f = [ordered]@{
Sel = $false # 复选框勾选状态(双向绑定)
Name = $Name
Command = $Cmd
Target = $tp
Arguments = $rt.Args
Kind = $Kind
Scope = $Scope
Label = $Label
Loc = $Loc
Enabled = $Enabled
StateText = $(if ($Enabled) { '已启用' } else { '已禁用' })
CanToggle = $CanToggle
CanEdit = $CanEdit
CanDelete = $CanDelete
Signer = $sg.Signer
SigStatus = $sg.Status
SigText = (Get-SigText $sg.Status)
Exists = $ex
ExistState = $es.State # 后台补签名后要用它重算风险
ExistText = $(switch ($es.State) { 'yes' { '存在' } 'no' { '文件不存在' } 'denied' { '无权读取(ACL 保护)' } default { '—' } })
Risk = $rk.Level
RiskText = $RISK_TEXT[$rk.Level]
RiskCell = "$($RISK_GLYPH[$rk.Level]) $($RISK_TEXT[$rk.Level])"
RiskRank = $RISK_RANK[$rk.Level]
RiskNote = $rk.Note
AiVerdict = '' # AI 分析结论(列表里显示摘要)
AiReport = $null # AI 分析全文,供详情面板展开
Extra = $Extra
}
# 字段清单只写一份:有 SmItem 就用带变更通知的真类型,没有就退回 PSCustomObject
if ($script:HasInpc) {
$o = [SmItem]::new()
foreach ($k in $f.Keys) { $o.$k = $f[$k] }
return $o
}
return [pscustomobject]$f
}
# ══════════════════════════════════════════════════════════════════
# 3. 查 —— 枚举
# ══════════════════════════════════════════════════════════════════
# 进度上报。前台跑时 $global:SM_PROGRESS 不存在,整个函数就是空操作;
# 后台 Runspace 里注入一个 synchronized hashtable,UI 线程的定时器直接读它。
function Set-Progress {
param([string]$Stage, [int]$Done = -1, [int]$Total = -1)
$p = $global:SM_PROGRESS
if ($null -eq $p) { return }
if ($Stage) { $p['Stage'] = $Stage }
if ($Done -ge 0) { $p['Done'] = $Done }
if ($Total -ge 0) { $p['Total'] = $Total }
}
function Get-AllStartupItems {
param([bool]$IncludeMsServices = $false)
$out = New-Object System.Collections.Generic.List[object]
$errs = New-Object System.Collections.Generic.List[string]
Set-Progress -Stage '读取注册表 Run 键' -Done 0 -Total 0
# try 必须包在每一条上,而不是整个循环外面:$ErrorActionPreference='Stop' 下
# 任何一条 New-Item2 抛错(Get-Command / Test-Path / 签名校验都可能抛),
# 循环外的 catch 会让该位置**剩余的全部条目**一起消失,界面看起来完全正常。
# 对一个用来排查持久化的工具来说这是最坏的失败模式,必须逐条隔离并计数。
# ── 注册表 Run 系列 ──
foreach ($L in $RUN_LOCS) {
try {
if (-not (Test-Path $L.Reg)) { continue }
$k = $null
try {
$k = Get-Item $L.Reg
$names = @($k.GetValueNames())
} finally { if ($k -is [IDisposable]) { $k.Dispose() } }
foreach ($n in $names) {
if ([string]::IsNullOrEmpty($n)) { continue }
try {
$kk = Get-Item $L.Reg
try { $v = [string]$kk.GetValue($n) } finally { if ($kk -is [IDisposable]) { $kk.Dispose() } }
$en = Get-ApprovedState -Hive $L.Ap -Sub $L.ApSub -Name $n
$out.Add((New-Item2 -Name $n -Cmd $v -Kind 'Run' -Scope $L.Scope -Label $L.Label `
-Loc $L.Reg -Enabled $en -CanToggle ([bool]$L.Ap) -CanEdit $true -CanDelete $true `
-Extra @{ Ap=$L.Ap; ApSub=$L.ApSub }))
} catch { $errs.Add("$($L.Label) → $n : $($_.Exception.Message)") }
}
} catch { $errs.Add("$($L.Label) : $($_.Exception.Message)") }
}
# ── 启动文件夹 ──
Set-Progress -Stage '读取启动文件夹' -Done $out.Count
$shell = New-Object -ComObject WScript.Shell
try {
foreach ($L in $FOLDER_LOCS) {
try {
if (-not $L.Path -or -not (Test-Path $L.Path)) { continue }
foreach ($f in Get-ChildItem -LiteralPath $L.Path -File -Force) {
try {
if ($f.Name -eq 'desktop.ini') { continue }
$cmd = $f.FullName
if ($f.Extension -ieq '.lnk') {
$lnk = $null
try {
$lnk = $shell.CreateShortcut($f.FullName)
$cmd = if ($lnk.Arguments) { "`"$($lnk.TargetPath)`" $($lnk.Arguments)" } else { "`"$($lnk.TargetPath)`"" }
} catch {
$errs.Add("$($L.Label) → $($f.Name) : 快捷方式解析失败")
} finally {
if ($lnk) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($lnk) }
}
}
$en = Get-ApprovedState -Hive $L.Ap -Sub 'StartupFolder' -Name $f.Name
$out.Add((New-Item2 -Name $f.Name -Cmd $cmd -Kind 'Folder' -Scope $L.Scope -Label $L.Label `
-Loc $f.FullName -Enabled $en -CanToggle $true -CanEdit $true -CanDelete $true `
-Extra @{ Ap=$L.Ap; ApSub='StartupFolder'; File=$f.FullName; Ext=$f.Extension }))
} catch { $errs.Add("$($L.Label) → $($f.Name) : $($_.Exception.Message)") }
}
} catch { $errs.Add("$($L.Label) : $($_.Exception.Message)") }
}
} finally {
if ($shell) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($shell) }
}
# ── 计划任务(登录 / 开机触发)──
Set-Progress -Stage '读取计划任务' -Done $out.Count
try {
foreach ($t in Get-ScheduledTask -ErrorAction SilentlyContinue) {
try {
$trg = @($t.Triggers | Where-Object { $_.CimClass.CimClassName -match 'Logon|Boot' })
if ($trg.Count -eq 0) { continue }
if ($t.TaskPath -like '\Microsoft\Windows\*') { continue } # 系统任务默认折叠
$act = @($t.Actions | ForEach-Object {
$a = [string]$_.Execute
if ($_.Arguments) { "`"$a`" $($_.Arguments)" } else { $a }
}) -join ' | '
if (-not $act.Trim()) { $act = '(COM 处理程序)' }
$kinds = ($trg | ForEach-Object { if ($_.CimClass.CimClassName -match 'Boot') {'开机'} else {'登录'} } | Select-Object -Unique) -join '+'
$out.Add((New-Item2 -Name $t.TaskName -Cmd $act -Kind 'Task' -Scope $kinds `
-Label "计划任务($kinds 触发)" -Loc ($t.TaskPath + $t.TaskName) `
-Enabled ($t.State -ne 'Disabled') -CanToggle $true -CanEdit $true -CanDelete $true `
-Extra @{ TaskName=$t.TaskName; TaskPath=$t.TaskPath; Desc=$t.Description; Author=$t.Author }))
} catch { $errs.Add("计划任务 → $($t.TaskName) : $($_.Exception.Message)") }
}
} catch { $errs.Add("计划任务 : $($_.Exception.Message)") }
# ── 服务 ──
# 只列 StartMode='Auto' 会让「禁用」变成单向死路:改成 Manual 后条目从列表消失,
# 界面里再也无法重新启用。把本工具管过的服务一并带出来,Enabled 反映真实 StartMode。
Set-Progress -Stage '读取服务' -Done $out.Count
try {
$managed = @(Get-ManagedServices)
foreach ($s in Get-CimInstance Win32_Service -ErrorAction SilentlyContinue) {
try {
$isAuto = ($s.StartMode -eq 'Auto')
$isMine = ($managed -contains $s.Name)
if (-not $isAuto -and -not $isMine) { continue }
$pn = [string]$s.PathName
if (-not $IncludeMsServices) {
$rt = Resolve-Target $pn
$tp = (Expand-Path $rt.Path).ToLowerInvariant()
if ($tp -match '\\windows\\(system32|syswow64)\\(svchost|lsass|spoolsv|searchindexer|sppsvc)\.exe$') { continue }
}
$mode = switch ([string]$s.StartMode) { 'Auto' {'自动'} 'Manual' {'手动'} 'Disabled' {'已禁用'} default { [string]$s.StartMode } }
$out.Add((New-Item2 -Name $s.Name -Cmd $pn -Kind 'Service' -Scope $s.StartName `
-Label "服务($mode·$($s.State))" -Loc "HKLM\SYSTEM\CurrentControlSet\Services\$($s.Name)" `
-Enabled $isAuto -CanToggle $true -CanEdit $false -CanDelete $true `
-Extra @{ SvcName=$s.Name; Display=$s.DisplayName; State=$s.State; Account=$s.StartName; StartMode=[string]$s.StartMode }))
} catch { $errs.Add("服务 → $($s.Name) : $($_.Exception.Message)") }
}
} catch { $errs.Add("服务 : $($_.Exception.Message)") }
Set-Progress -Stage '整理结果' -Done $out.Count
$script:LoadErrors = @($errs)
# 注意:这里**不能**写 `return ,$out.ToArray()`。加逗号会让函数只输出一个
# 「装着数组的对象」,调用方 `@(Get-AllStartupItems) | Where-Object {...}`
# 拿到的 $_ 就是整个数组,$_.Name 变成全部名称的集合,过滤条件恒真 ——
# 结果是「找一条」返回全部条目,后续删除/改名会打到别的启动项上。
# 调用方一律用 @() 包裹来处理单元素情形(Load-Items 已经这么做)。
return $out.ToArray()
}
# ══════════════════════════════════════════════════════════════════
# 4. 回滚日志
# ══════════════════════════════════════════════════════════════════
# 哪些记录「撤销上一步」真的能还原。计划任务 / 服务的删除、脚本文件的删除、
# 快捷方式的编辑都恢复不了 —— 提前标出来,避免它们占住「上一步」的位置,
# 让真正可撤销的操作被顶掉。
function Test-RecordUndoable {
param([string]$Action, [string]$Kind, $Extra)
switch ($Action) {
'delete' {
switch ($Kind) {
'Run' { return $true }
'Folder' { return ([string]$Extra.Ext -ieq '.lnk') }
default { return $false }
}
}
'edit' { return ($Kind -in @('Run','Task')) }
}
return $false
}
function New-JournalRecord {
param($Item, [string]$Action, [string]$Batch = '', [string]$NewName = '')
[pscustomobject]@{
Time = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
Action = $Action
Batch = $Batch # 同一次批量操作共用一个批次号,供整批撤销
Name = $Item.Name; Command = $Item.Command; Kind = $Item.Kind
Scope = $Item.Scope; Loc = $Item.Loc; Enabled = $Item.Enabled
NewName = $NewName # 改名时的新键名,撤销要把它删掉,否则新旧两条同时开机启动
Undoable = (Test-RecordUndoable -Action $Action -Kind $Item.Kind -Extra $Item.Extra)
Extra = $Item.Extra
}
}
# 读取原始日志。解析失败时**不能**当成空数组返回给写入方 ——
# 那会让下一次写入用一条新记录覆盖掉整个历史。这里返回 $null 表示「损坏」,
# 由调用方决定是另存还是中止。
function Read-JournalRaw {
if (-not (Test-Path $script:Journal)) { return ,@() }
try {
$txt = Get-Content $script:Journal -Raw -Encoding UTF8
if ([string]::IsNullOrWhiteSpace($txt)) { return ,@() }
return ,@($txt | ConvertFrom-Json)
} catch { return $null }
}
function Read-Journal {
$r = Read-JournalRaw
if ($null -eq $r) { return ,@() }
return ,$r
}
$script:JOURNAL_MAX = 2000 # 超出后从最旧的开始丢弃,避免日志无上限增长
# 一次读、一次写。批量删除 50 项原本是 50 次全量 JSON 往返(O(n²))。
function Write-JournalRecords {
param([object[]]$Records)
if (-not $Records -or $Records.Count -eq 0) { return }
$all = Read-JournalRaw
if ($null -eq $all) {
# 日志损坏:另存备份后重新开始,既不覆盖丢失历史,也不阻塞本次操作
$bak = "$script:Journal.corrupt-$(Get-Date -Format 'yyyyMMdd_HHmmss')"
try { Move-Item -LiteralPath $script:Journal -Destination $bak -Force } catch { }
$all = @()
$script:JournalWarning = "回滚日志此前已损坏,已另存为 $bak 并重新开始记录 —— 该时间点之前的操作不再可撤销。"
}
$all = @($all) + @($Records)
if ($all.Count -gt $script:JOURNAL_MAX) { $all = @($all[($all.Count - $script:JOURNAL_MAX)..($all.Count - 1)]) }
($all | ConvertTo-Json -Depth 6) | Set-Content $script:Journal -Encoding UTF8
}
function Write-Journal {
param($Item, [string]$Action, [string]$Batch = '', [string]$NewName = '')
Write-JournalRecords -Records @((New-JournalRecord -Item $Item -Action $Action -Batch $Batch -NewName $NewName))
}
# 取「上一步」——若末条属于某个批次,则整批一起返回,避免删 9 项要点 9 次撤销
function Get-LastJournalGroup {
$all = Read-Journal
if ($all.Count -eq 0) { return @() }
$last = $all[-1]
if ([string]::IsNullOrEmpty($last.Batch)) { return @($last) }
return @($all | Where-Object { $_.Batch -eq $last.Batch })
}
function Pop-JournalGroup {
param([int]$Count = 1)
$all = Read-Journal
if ($all.Count -le $Count) { Remove-Item $script:Journal -Force -ErrorAction SilentlyContinue; return }
($all[0..($all.Count - $Count - 1)] | ConvertTo-Json -Depth 6) | Set-Content $script:Journal -Encoding UTF8
}
# ══════════════════════════════════════════════════════════════════
# 5. 增 / 删 / 改
# ══════════════════════════════════════════════════════════════════
function Add-StartupItem {
# 注意:参数名不可叫 $Args —— 它与 PowerShell 自动变量 $args 冲突,会导致绑定失效。
param([string]$Kind, [string]$Scope, [string]$Name, [string]$Exe, [string]$Arguments)
$cmd = if ($Arguments) { "`"$Exe`" $Arguments" } else { "`"$Exe`"" }
switch ($Kind) {
'Run' {
$L = $RUN_LOCS | Where-Object { $_.Scope -eq $Scope } | Select-Object -First 1
if (-not $L) { throw "未知的注册表位置:$Scope" }
if (-not (Test-Path $L.Reg)) { New-Item -Path $L.Reg -Force | Out-Null }
Set-ItemProperty -Path $L.Reg -Name $Name -Value $cmd -Type String -Force
if ($L.Ap) { Set-ApprovedState -Hive $L.Ap -Sub $L.ApSub -Name $Name -Enabled $true }
}
'Folder' {
$L = $FOLDER_LOCS | Where-Object { $_.Scope -eq $Scope } | Select-Object -First 1
if (-not $L) { throw "未知的启动文件夹:$Scope" }
$lnkPath = Join-Path $L.Path "$Name.lnk"
$sh = New-Object -ComObject WScript.Shell
$lnk = $sh.CreateShortcut($lnkPath)
$lnk.TargetPath = $Exe
if ($Arguments) { $lnk.Arguments = $Arguments }
$lnk.WorkingDirectory = Split-Path $Exe -Parent
$lnk.Save()
}
'Task' {
$a = if ($Arguments) { New-ScheduledTaskAction -Execute $Exe -Argument $Arguments }
else { New-ScheduledTaskAction -Execute $Exe }
$t = New-ScheduledTaskTrigger -AtLogOn
$p = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -RunLevel Highest
$s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)
Register-ScheduledTask -TaskName $Name -Action $a -Trigger $t -Principal $p -Settings $s -Force | Out-Null
}
default { throw "不支持新建该类型:$Kind" }
}
}
function Remove-StartupItem {
# SkipJournal:批量删除时由调用方一次性预写全部记录(仍在任何破坏性操作之前),
# 避免每删一项就整文件读写一遍日志。
param($Item, [string]$Batch = '', [switch]$SkipJournal)
if (-not $SkipJournal) { Write-Journal -Item $Item -Action 'delete' -Batch $Batch }
switch ($Item.Kind) {
'Run' {
Remove-RegValue -Path $Item.Loc -Name $Item.Name
$ap = Get-ApprovedKeyPath -Hive $Item.Extra.Ap -Sub $Item.Extra.ApSub
if ($ap -and (Test-Path $ap)) { Remove-RegValue -Path $ap -Name $Item.Name -Quiet }
}
'Folder' {
# 送回收站而非直接抹除:回滚日志只能重建 .lnk,脚本文件的内容重建不出来,
# 回收站是这类文件唯一的第二道防线。
try {
Add-Type -AssemblyName Microsoft.VisualBasic -ErrorAction Stop
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile(
$Item.Extra.File,
[Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,
[Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)
} catch {
Remove-Item -LiteralPath $Item.Extra.File -Force # 回收站不可用时退回硬删
}
}
'Task' { Unregister-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $Item.Extra.TaskPath -Confirm:$false }
'Service' {
if ($Item.Extra.State -eq 'Running') { Stop-Service -Name $Item.Extra.SvcName -Force -ErrorAction SilentlyContinue }
& "$([Environment]::SystemDirectory)\sc.exe" delete $Item.Extra.SvcName | Out-Null
if ($LASTEXITCODE -ne 0) { throw "sc.exe delete 返回 $LASTEXITCODE(受保护的服务无法删除)" }
Set-ManagedService -Name $Item.Extra.SvcName -Tracked $false
}
}
}
function Set-StartupItemEnabled {
param($Item, [bool]$Enabled)
switch ($Item.Kind) {
'Run' { if (-not $Item.Extra.Ap) { throw '该位置不支持启用/禁用开关,只能删除' }
Set-ApprovedState -Hive $Item.Extra.Ap -Sub $Item.Extra.ApSub -Name $Item.Name -Enabled $Enabled }
'Folder' { Set-ApprovedState -Hive $Item.Extra.Ap -Sub 'StartupFolder' -Name $Item.Name -Enabled $Enabled }
'Task' { if ($Enabled) { Enable-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $Item.Extra.TaskPath | Out-Null }
else { Disable-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $Item.Extra.TaskPath | Out-Null } }
'Service'{ $m = if ($Enabled) { 'Automatic' } else { 'Manual' }
Set-Service -Name $Item.Extra.SvcName -StartupType $m
# 记住被我们改成手动的服务,否则下次刷新它就从列表里消失了
Set-ManagedService -Name $Item.Extra.SvcName -Tracked (-not $Enabled) }
}
}
function Update-StartupItem {
param($Item, [string]$NewName, [string]$NewCmd)
Write-Journal -Item $Item -Action 'edit' -NewName $NewName
$renamed = ($NewName -ne $Item.Name)
switch ($Item.Kind) {
'Run' {
# 必须在删除旧记录之前读取实时启用状态:
# · 不能信任传入对象缓存的 Enabled(「先禁用再编辑」会被悄悄重新启用)
# · 也不能在 Remove 之后再读(记录已消失,会退回默认「启用」)
$live = $true
if ($Item.Extra.Ap) {
$live = Get-ApprovedState -Hive $Item.Extra.Ap -Sub $Item.Extra.ApSub -Name $Item.Name
}
if ($renamed) {
Remove-RegValue -Path $Item.Loc -Name $Item.Name
$ap = Get-ApprovedKeyPath -Hive $Item.Extra.Ap -Sub $Item.Extra.ApSub
if ($ap -and (Test-Path $ap)) { Remove-RegValue -Path $ap -Name $Item.Name -Quiet }
}
Set-ItemProperty -Path $Item.Loc -Name $NewName -Value $NewCmd -Type String -Force
if ($Item.Extra.Ap) {
Set-ApprovedState -Hive $Item.Extra.Ap -Sub $Item.Extra.ApSub -Name $NewName -Enabled $live
}
}
'Folder' {
if ($Item.Extra.Ext -ine '.lnk') {
throw '仅支持编辑快捷方式(.lnk)。脚本文件请用「定位文件」打开后直接编辑其内容。'
}
# StartupApproved\StartupFolder 以「文件名」为键,改名时必须把状态迁移过去
$live = Get-ApprovedState -Hive $Item.Extra.Ap -Sub 'StartupFolder' -Name $Item.Name
$rt = Resolve-Target $NewCmd
$tgt = Expand-Path $rt.Path
$sh = New-Object -ComObject WScript.Shell
$lnk = $sh.CreateShortcut($Item.Extra.File)
$lnk.TargetPath = $tgt
$lnk.Arguments = $rt.Args
if ($tgt) {
$parent = Split-Path $tgt -Parent
if ($parent) { $lnk.WorkingDirectory = $parent }
}
$lnk.Save()
if ($renamed) {
$leaf = if ($NewName -match '\.lnk$') { $NewName } else { "$NewName.lnk" }
Rename-Item -LiteralPath $Item.Extra.File -NewName $leaf -Force
$ap = Get-ApprovedKeyPath -Hive $Item.Extra.Ap -Sub 'StartupFolder'
if ($ap -and (Test-Path $ap)) { Remove-RegValue -Path $ap -Name $Item.Name -Quiet }
Set-ApprovedState -Hive $Item.Extra.Ap -Sub 'StartupFolder' -Name $leaf -Enabled $live
}
}
'Task' {
$tp = [string]$Item.Extra.TaskPath
if ($tp -like '\Microsoft\Windows\*') { throw '系统计划任务不允许在此修改。' }
$t = Get-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $tp -ErrorAction Stop
# 多动作任务在这里只能整体替换成一条,会丢掉其余动作 —— 明确拒绝
if (@($t.Actions).Count -gt 1) {
throw "该任务有 $(@($t.Actions).Count) 个动作,在此编辑会丢掉其余动作。请用「打开位置」在任务计划程序中修改。"
}
$rt = Resolve-Target $NewCmd
$exe = Expand-Path $rt.Path
if (-not $exe) { throw '命令为空。' }
$act = if ($rt.Args) { New-ScheduledTaskAction -Execute $exe -Argument $rt.Args }
else { New-ScheduledTaskAction -Execute $exe }
if ($renamed) {
# 任务名就是标识,改名只能「按同一份定义在新名下重建,再注销旧的」。
# 顺序不能反:先建后删,中途失败也不会把原任务弄丢。
Register-ScheduledTask -TaskName $NewName -TaskPath $tp -Action $act `
-Trigger $t.Triggers -Principal $t.Principal -Settings $t.Settings -Force | Out-Null
Unregister-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $tp -Confirm:$false
} else {
Set-ScheduledTask -TaskName $Item.Extra.TaskName -TaskPath $tp -Action $act | Out-Null
}
}
default { throw "「$($Item.Label)」类型不支持在此编辑。" }
}
}
function Restore-JournalRecord {
param($r)
# 恢复会以管理员身份按记录内容写系统,日志文件本身却是可被篡改的普通文件 ——
# 先确认目标在本工具管理的位置白名单内。
Assert-JournalTarget $r
if ($r.Action -eq 'delete') {
switch ($r.Kind) {
'Run' {
if (-not (Test-Path $r.Loc)) { New-Item -Path $r.Loc -Force | Out-Null }
Set-ItemProperty -Path $r.Loc -Name $r.Name -Value $r.Command -Type String -Force
if ($r.Extra.Ap) { Set-ApprovedState -Hive $r.Extra.Ap -Sub $r.Extra.ApSub -Name $r.Name -Enabled ([bool]$r.Enabled) }
}
'Folder' {
if ($r.Extra.Ext -ine '.lnk') {
throw "脚本文件的内容无法自动恢复:$($r.Extra.File)(请查回收站)"
}
$rt = Resolve-Target $r.Command
$tgt = Expand-Path $rt.Path
$sh = New-Object -ComObject WScript.Shell
$lnk = $sh.CreateShortcut($r.Extra.File)
$lnk.TargetPath = $tgt
$lnk.Arguments = $rt.Args
if ($tgt) { $p = Split-Path $tgt -Parent; if ($p) { $lnk.WorkingDirectory = $p } }
$lnk.Save()
Set-ApprovedState -Hive $r.Extra.Ap -Sub 'StartupFolder' -Name $r.Name -Enabled ([bool]$r.Enabled)
}
default { throw "计划任务 / 服务的删除无法自动撤销(需手动重建)" }
}
return
}
if ($r.Action -eq 'edit') {
if ($r.Kind -eq 'Task') {
$tp = [string]$r.Extra.TaskPath
$new = [string]$r.NewName
$rt = Resolve-Target $r.Command
$exe = Expand-Path $rt.Path
$act = if ($rt.Args) { New-ScheduledTaskAction -Execute $exe -Argument $rt.Args }
else { New-ScheduledTaskAction -Execute $exe }
if ($new -and $new -ne [string]$r.Name) {
# 改过名:拿改名后那个任务的定义,在原名下重建,再把新名注销
$cur = Get-ScheduledTask -TaskName $new -TaskPath $tp -ErrorAction Stop
Register-ScheduledTask -TaskName $r.Name -TaskPath $tp -Action $act `
-Trigger $cur.Triggers -Principal $cur.Principal -Settings $cur.Settings -Force | Out-Null
Unregister-ScheduledTask -TaskName $new -TaskPath $tp -Confirm:$false
} else {
Set-ScheduledTask -TaskName $r.Name -TaskPath $tp -Action $act | Out-Null
}
return
}
if ($r.Kind -eq 'Run') {
if (-not (Test-Path $r.Loc)) { New-Item -Path $r.Loc -Force | Out-Null }
# 改名的撤销必须先删掉新键,否则新旧两条会同时留在 Run 里一起开机启动
$new = [string]$r.NewName
if ($new -and $new -ne [string]$r.Name) {
Remove-RegValue -Path $r.Loc -Name $new -Quiet
$apk = Get-ApprovedKeyPath -Hive $r.Extra.Ap -Sub $r.Extra.ApSub
if ($apk -and (Test-Path $apk)) { Remove-RegValue -Path $apk -Name $new -Quiet }
}
Set-ItemProperty -Path $r.Loc -Name $r.Name -Value $r.Command -Type String -Force
# 删除的撤销会还原启用/禁用状态,编辑的撤销此前漏了这一步
if ($r.Extra.Ap) { Set-ApprovedState -Hive $r.Extra.Ap -Sub $r.Extra.ApSub -Name $r.Name -Enabled ([bool]$r.Enabled) }
return
}
throw "该类型的编辑无法自动撤销"
}
throw "未知的日志动作:$($r.Action)"
}
# 撤销失败 / 本就不可撤销的记录不能随出栈一起丢掉 —— 那是这些条目仅存的备份。