-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheGPU.ps1
More file actions
1344 lines (1131 loc) · 51 KB
/
eGPU.ps1
File metadata and controls
1344 lines (1131 loc) · 51 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
# eGPU Auto Hot-Plug Manager
# This script continuously monitors for eGPU physical reconnection and automatically enables it
# Designed to run at startup and handle all eGPU hot-plug scenarios
# VERSION CONSTANT - Update this when releasing new versions
$SCRIPT_VERSION = "2.3.0"
<#
.SYNOPSIS
eGPU Auto-Enable Tool - Automatically re-enables eGPU after hot-plugging on Windows
.DESCRIPTION
This tool monitors your external GPU and automatically enables it whenever you reconnect it after safe-removal.
It eliminates the need to manually enable the eGPU from Device Manager.
.NOTES
File Name : eGPU.ps1
Prerequisite : PowerShell 7.0 or later
Requires Admin : Yes (for pnputil device enabling)
Version : 2.2.0
Repository : https://github.com/Bananz0/eGPUae
#>
# ===== CONFIGURATION =====
# Paths
$installPath = Join-Path $env:USERPROFILE ".egpu-manager"
$configPath = Join-Path $installPath "egpu-config.json"
$logPath = Join-Path $installPath "egpu-manager.log"
$lastUpdateCheckFile = Join-Path $installPath "last-update-check.txt"
# Polling and logging configuration
$pollInterval = 2 # seconds
$maxLogSizeKB = 500
$maxLogLines = 1000
# Runtime state file for crash recovery
$runtimeStatePath = Join-Path $installPath "runtime-state.json"
# Update check configuration
$updateCheckInterval = 86400 # Check once per day (in seconds)
# Display sleep management
$savedDisplayTimeout = $null
$displaySleepManaged = $false
# Lid close action management
$savedLidCloseAction = $null
$lidCloseManaged = $false
# User preferences (loaded from config)
$userDisplayTimeoutMinutes = $null
$userLidCloseAction = $null
# Power plan management
$savedPowerPlan = $null
$powerPlanManaged = $false
$eGPUPowerPlanGuid = $null
$originalPowerPlanGuid = $null # Original plan from before eGPU plan was created
# New feature settings (loaded from config)
$script:preventPCSleep = $false
$script:pcSleepTimeoutMinutes = $null
$script:eGPUDisplayTimeoutMinutes = $null
$script:enableNotifications = $true
$script:trackStatistics = $false
$script:autoLaunchApps = @()
$script:closeLaunchersOnDisconnect = $false
$script:enableSafeEjectHotkey = $false
$script:preDisconnectWarning = $true
# Runtime tracking
$script:launchedApps = @() # Track which apps we launched for closing later
$script:connectionStartTime = $null # Track current session start time
# =========================
# Save runtime state for crash recovery
function Save-RuntimeState {
param(
[int]$DisplayTimeout,
[int]$LidCloseAction,
[string]$PowerPlan
)
try {
$state = @{}
# Load existing state if it exists
if (Test-Path $runtimeStatePath) {
$state = Get-Content $runtimeStatePath | ConvertFrom-Json -AsHashtable
}
# Update with new values
if ($PSBoundParameters.ContainsKey('DisplayTimeout')) {
$state.SavedDisplayTimeout = $DisplayTimeout
}
if ($PSBoundParameters.ContainsKey('LidCloseAction')) {
$state.SavedLidCloseAction = $LidCloseAction
}
if ($PSBoundParameters.ContainsKey('PowerPlan')) {
$state.SavedPowerPlan = $PowerPlan
}
$state | ConvertTo-Json | Set-Content $runtimeStatePath -ErrorAction SilentlyContinue
}
catch {
Write-Error "Failed to save runtime state: $_"
}
}
# Clear runtime state items
function Clear-RuntimeState {
param(
[switch]$DisplayTimeout,
[switch]$LidCloseAction,
[switch]$PowerPlan,
[switch]$All
)
try {
if ($All -or -not (Test-Path $runtimeStatePath)) {
Remove-Item $runtimeStatePath -ErrorAction SilentlyContinue
return
}
$state = Get-Content $runtimeStatePath | ConvertFrom-Json -AsHashtable
if ($DisplayTimeout) { $state.Remove('SavedDisplayTimeout') }
if ($LidCloseAction) { $state.Remove('SavedLidCloseAction') }
if ($PowerPlan) { $state.Remove('SavedPowerPlan') }
if ($state.Count -eq 0) {
Remove-Item $runtimeStatePath -ErrorAction SilentlyContinue
}
else {
$state | ConvertTo-Json | Set-Content $runtimeStatePath -ErrorAction SilentlyContinue
}
}
catch {
Write-Error "Failed to clear runtime state: $_"
}
}
# Restore settings on startup if script exited unexpectedly
function Restore-PreviousState {
param([string]$currentEGPUState)
if (-not (Test-Path $runtimeStatePath)) {
return
}
try {
$state = Get-Content $runtimeStatePath | ConvertFrom-Json
$restored = $false
# Only restore if eGPU is not currently present-ok
# If eGPU is connected and working, we're in normal operation - clear state and continue
if ($currentEGPUState -eq "present-ok") {
Write-Log "eGPU connected on startup, clearing stale runtime state" "INFO"
Clear-RuntimeState -All
return
}
# eGPU is absent or disabled - restore saved settings from crash/reboot
Write-Log "Detected runtime state from previous session, restoring settings..." "INFO"
# Restore display timeout
if ($state.PSObject.Properties.Name -contains 'SavedDisplayTimeout') {
$timeoutMinutes = if ($null -ne $script:userDisplayTimeoutMinutes) {
$script:userDisplayTimeoutMinutes
}
else {
[math]::Ceiling($state.SavedDisplayTimeout / 60)
}
powercfg /change monitor-timeout-ac $timeoutMinutes | Out-Null
Write-Log "Restored display timeout: $timeoutMinutes minutes" "INFO"
$restored = $true
}
# Restore lid close action
if ($state.PSObject.Properties.Name -contains 'SavedLidCloseAction') {
try {
$powerNamespace = @{ Namespace = 'root\cimv2\power' }
$curPlan = Get-CimInstance @powerNamespace -Class Win32_PowerPlan -Filter "IsActive = TRUE"
$lidSetting = Get-CimInstance @powerNamespace -ClassName Win32_Powersetting -Filter "ElementName = 'Lid close action'"
if ($curPlan -and $lidSetting) {
$planGuid = [Regex]::Matches($curPlan.InstanceId, "{.*}").Value
$lidGuid = [Regex]::Matches($lidSetting.InstanceID, "{.*}").Value
$pluggedInLidSetting = Get-CimInstance @powerNamespace -ClassName Win32_PowerSettingDataIndex `
-Filter "InstanceID = 'Microsoft:PowerSettingDataIndex\\$planGuid\\AC\\$lidGuid'"
if ($pluggedInLidSetting) {
# Use user preference if set, otherwise use saved value
$restoreValue = if ($null -ne $script:userLidCloseAction) {
$script:userLidCloseAction
}
else {
$state.SavedLidCloseAction
}
$pluggedInLidSetting | Set-CimInstance -Property @{ SettingIndexValue = $restoreValue }
$curPlan | Invoke-CimMethod -MethodName Activate | Out-Null
$actionName = switch ($restoreValue) { 0 { "Do Nothing" } 1 { "Sleep" } 2 { "Hibernate" } 3 { "Shut Down" } default { "Unknown" } }
Write-Log "Restored lid close action: $actionName" "INFO"
$restored = $true
}
}
}
catch {
Write-Log "Could not restore lid close action: $_" "WARNING"
}
}
# Restore power plan
if ($state.PSObject.Properties.Name -contains 'SavedPowerPlan') {
powercfg -SETACTIVE $state.SavedPowerPlan | Out-Null
Write-Log "Restored power plan from previous session" "INFO"
$restored = $true
}
if ($restored) {
Write-Log "Recovery: Settings restored after unexpected exit/reboot" "SUCCESS"
Show-Notification -Title "eGPU Manager Started" -Message "Power settings restored to normal (eGPU not connected)"
}
# Clear runtime state after successful restore
Clear-RuntimeState -All
}
catch {
Write-Log "Could not restore previous state: $_" "WARNING"
}
}
# Logging function with automatic rotation
function Write-Log {
param(
[string]$Message,
[string]$Level = "INFO" # INFO, SUCCESS, WARNING, ERROR
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
# Write to console (color-coded)
$color = switch ($Level) {
"SUCCESS" { "Green" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
default { "White" }
}
Write-Host $logEntry -ForegroundColor $color
# Append to log file
try {
Add-Content -Path $logPath -Value $logEntry -ErrorAction Stop
# Check log size and rotate if needed
$logFile = Get-Item $logPath -ErrorAction SilentlyContinue
if ($logFile -and ($logFile.Length / 1KB) -gt $maxLogSizeKB) {
# Read last N lines
$allLines = Get-Content $logPath
$linesToKeep = $allLines | Select-Object -Last $maxLogLines
# Create backup of old log
$backupPath = Join-Path $installPath "egpu-manager.old.log"
if (Test-Path $backupPath) {
Remove-Item $backupPath -Force
}
Move-Item $logPath $backupPath -Force
# Write kept lines to new log
$linesToKeep | Set-Content $logPath
$savedKB = [math]::Round(($logFile.Length - (Get-Item $logPath).Length) / 1KB, 2)
Add-Content -Path $logPath -Value "[$timestamp] [INFO] Log rotated. Saved ${savedKB}KB. Kept last $maxLogLines lines."
}
}
catch {
Write-Error "Failed to write log: $_"
}
}
# Manage display sleep settings
function Set-DisplaySleep {
param(
[bool]$Disable
)
try {
if ($Disable) {
# If already managing, do nothing
if ($script:displaySleepManaged) {
Write-Log "Set-DisplaySleep: Already managing display sleep, skipping disable." "INFO"
return $true
}
# Read raw line with Current AC Power Setting Index
$rawLine = powercfg /q SCHEME_CURRENT SUB_VIDEO VIDEOIDLE |
Select-String "Current AC Power Setting Index" -SimpleMatch |
ForEach-Object { $_.Line.Trim() } | Select-Object -First 1
if (-not $rawLine) {
Write-Log "Set-DisplaySleep: Could not read current AC timeout from powercfg." "WARNING"
return $false
}
# Extract hex value (e.g. 0x00000078)
if ($rawLine -match "0x[0-9A-Fa-f]+") {
$hex = $Matches[0]
}
else {
# If line contains ":" parted value like "Current AC Power Setting Index: 0x00000078"
$parts = $rawLine -split ":"
$maybe = $parts[-1].Trim()
if ($maybe -match "0x[0-9A-Fa-f]+") {
$hex = $Matches[0]
}
else {
Write-Log "Set-DisplaySleep: Failed to parse hex timeout from: '$rawLine'." "WARNING"
return $false
}
}
# Convert hex string to integer seconds
try {
$seconds = [Convert]::ToInt32($hex, 16)
}
catch {
Write-Log "Set-DisplaySleep: Failed to convert hex '$hex' to integer: $_" "WARNING"
return $false
}
# Save seconds in script scope for restore
$script:savedDisplayTimeout = $seconds
# Persist to config file for crash recovery
Save-RuntimeState -DisplayTimeout $seconds
if ($seconds -ne 0) {
powercfg /change monitor-timeout-ac 0 | Out-Null
$script:displaySleepManaged = $true
Write-Log "Display sleep disabled (saved timeout: $seconds seconds)" "INFO"
return $true
}
else {
Write-Log "Set-DisplaySleep: AC timeout already set to 'never' (0 seconds). Not changing." "INFO"
$script:displaySleepManaged = $true
# Still mark as managed so we can restore user preference later
# Use user preference or default to a sensible value
if ($null -eq $script:savedDisplayTimeout -or $script:savedDisplayTimeout -eq 0) {
# Set a default from user preference or use 5 minutes
if ($null -ne $script:userDisplayTimeoutMinutes -and $script:userDisplayTimeoutMinutes -gt 0) {
$script:savedDisplayTimeout = $script:userDisplayTimeoutMinutes * 60
}
else {
$script:savedDisplayTimeout = 300 # 5 minutes default
}
}
return $true
}
}
else {
# Restore setting based on user preference or saved value
if ($script:displaySleepManaged) {
# Use user preference if set, otherwise use saved value
if ($null -ne $script:userDisplayTimeoutMinutes) {
$timeoutMinutes = $script:userDisplayTimeoutMinutes
Write-Log "Restoring display sleep to user preference: $timeoutMinutes minutes" "INFO"
}
elseif ($null -ne $script:savedDisplayTimeout) {
$timeoutMinutes = [math]::Ceiling($script:savedDisplayTimeout / 60)
if ($script:savedDisplayTimeout -eq 0) {
$timeoutMinutes = 0
}
Write-Log "Restoring display sleep to saved value: $timeoutMinutes minutes (original: $($script:savedDisplayTimeout) seconds)" "INFO"
}
else {
Write-Log "Set-DisplaySleep: Nothing to restore (no saved or user preference value)." "INFO"
return $false
}
powercfg /change monitor-timeout-ac $timeoutMinutes | Out-Null
$script:displaySleepManaged = $false
# Clear from runtime state
Clear-RuntimeState -DisplayTimeout
return $true
}
else {
Write-Log "Set-DisplaySleep: Nothing to restore (not previously managed or no saved value)." "INFO"
return $false
}
}
}
catch {
Write-Log "Failed to manage display sleep: $_" "WARNING"
return $false
}
}
# Manage power plan switching
function Set-PowerPlan {
param(
[bool]$UseEGPUPlan
)
try {
if ($UseEGPUPlan) {
# If already managing, do nothing
if ($script:powerPlanManaged) {
return $true
}
# Check if eGPU power plan exists
if ($null -eq $script:eGPUPowerPlanGuid) {
Write-Log "eGPU power plan not configured, skipping power plan switch" "INFO"
return $false
}
# Get current active power plan
try {
$currentPlan = powercfg -GETACTIVESCHEME
if ($currentPlan -match "([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})") {
$currentPlanGuid = $Matches[1]
# If already on eGPU plan, still mark as managed (so we can restore later)
if ($currentPlanGuid -eq $script:eGPUPowerPlanGuid) {
Write-Log "Already using eGPU power plan" "INFO"
$script:powerPlanManaged = $true
# Priority: runtime state > original plan from config > Balanced default
if ($null -eq $script:savedPowerPlan) {
if ($null -ne $script:originalPowerPlanGuid) {
$script:savedPowerPlan = $script:originalPowerPlanGuid
Write-Log "Will restore to original plan from config" "INFO"
}
else {
# Fallback to Balanced plan GUID
$script:savedPowerPlan = "381b4222-f694-41f0-9685-ff5bb260df2e"
Write-Log "Will restore to Balanced plan (default)" "INFO"
}
}
return $true
}
# Save current plan to restore later
$script:savedPowerPlan = $currentPlanGuid
# Persist to config file for crash recovery
Save-RuntimeState -PowerPlan $script:savedPowerPlan
}
}
catch {
Write-Log "Could not detect current power plan: $_" "WARNING"
return $false
}
# Switch to eGPU power plan
powercfg -SETACTIVE $script:eGPUPowerPlanGuid | Out-Null
$script:powerPlanManaged = $true
Write-Log "Switched to eGPU High Performance power plan" "SUCCESS"
return $true
}
else {
# Restore original power plan
if ($script:powerPlanManaged -and $null -ne $script:savedPowerPlan) {
powercfg -SETACTIVE $script:savedPowerPlan | Out-Null
Write-Log "Restored original power plan" "INFO"
$script:powerPlanManaged = $false
# Clear from runtime state
Clear-RuntimeState -PowerPlan
return $true
}
return $false
}
}
catch {
Write-Log "Failed to manage power plan: $_" "WARNING"
return $false
}
}
# Check if external monitors are connected
function Test-ExternalMonitor {
try {
$monitors = Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams |
Where-Object { $_.Active -eq $true }
# More than 1 active monitor = external monitor(s) present
return ($monitors.Count -gt 1)
}
catch {
Write-Log "Failed to check external monitors: $_" "WARNING"
return $false
}
}
# Manage lid close action
function Set-LidCloseAction {
param(
[bool]$DisableSleep
)
# Source: https://superuser.com/a/1700937 by KyleMit (CC BY-SA 4.0)
try {
$powerNamespace = @{ Namespace = 'root\cimv2\power' }
if ($DisableSleep) {
# If already managing, do nothing
if ($script:lidCloseManaged) {
return $true
}
# Get active plan and lid setting
$curPlan = Get-CimInstance @powerNamespace -Class Win32_PowerPlan -Filter "IsActive = TRUE"
$lidSetting = Get-CimInstance @powerNamespace -ClassName Win32_Powersetting -Filter "ElementName = 'Lid close action'"
if (-not $curPlan -or -not $lidSetting) {
Write-Log "Lid close action setting not available on this device" "INFO"
return $false
}
# Get GUIDs
$planGuid = [Regex]::Matches($curPlan.InstanceId, "{.*}").Value
$lidGuid = [Regex]::Matches($lidSetting.InstanceID, "{.*}").Value
# Get plugged in (AC) lid setting
$pluggedInLidSetting = Get-CimInstance @powerNamespace -ClassName Win32_PowerSettingDataIndex `
-Filter "InstanceID = 'Microsoft:PowerSettingDataIndex\\$planGuid\\AC\\$lidGuid'"
if (-not $pluggedInLidSetting) {
Write-Log "Could not retrieve AC lid close setting" "WARNING"
return $false
}
# Save current action
$script:savedLidCloseAction = $pluggedInLidSetting.SettingIndexValue
# Persist to config file for crash recovery
Save-RuntimeState -LidCloseAction $script:savedLidCloseAction
# Set to "Do Nothing" (0) if not already
if ($script:savedLidCloseAction -ne 0) {
$pluggedInLidSetting | Set-CimInstance -Property @{ SettingIndexValue = 0 }
$curPlan | Invoke-CimMethod -MethodName Activate | Out-Null
$script:lidCloseManaged = $true
$actionName = switch ($script:savedLidCloseAction) { 0 { "Do Nothing" } 1 { "Sleep" } 2 { "Hibernate" } 3 { "Shut Down" } default { "Unknown" } }
Write-Log "Lid close action set to 'Do Nothing' (saved: $actionName)" "INFO"
return $true
}
else {
Write-Log "Lid close action already set to 'Do Nothing'" "INFO"
$script:lidCloseManaged = $true
# Still mark as managed so we can restore user preference later
# Use user preference or default to Sleep
if ($null -eq $script:savedLidCloseAction -or $script:savedLidCloseAction -eq 0) {
if ($null -ne $script:userLidCloseAction) {
$script:savedLidCloseAction = $script:userLidCloseAction
}
else {
$script:savedLidCloseAction = 1 # Default to Sleep
}
}
return $true
}
}
else {
# Restore original setting
if ($script:lidCloseManaged -and $null -ne $script:savedLidCloseAction) {
$curPlan = Get-CimInstance @powerNamespace -Class Win32_PowerPlan -Filter "IsActive = TRUE"
$lidSetting = Get-CimInstance @powerNamespace -ClassName Win32_Powersetting -Filter "ElementName = 'Lid close action'"
$planGuid = [Regex]::Matches($curPlan.InstanceId, "{.*}").Value
$lidGuid = [Regex]::Matches($lidSetting.InstanceID, "{.*}").Value
$pluggedInLidSetting = Get-CimInstance @powerNamespace -ClassName Win32_PowerSettingDataIndex `
-Filter "InstanceID = 'Microsoft:PowerSettingDataIndex\\$planGuid\\AC\\$lidGuid'"
# Use user preference if set, otherwise use saved value
$restoreValue = if ($null -ne $script:userLidCloseAction) {
$script:userLidCloseAction
}
else {
$script:savedLidCloseAction
}
$pluggedInLidSetting | Set-CimInstance -Property @{ SettingIndexValue = $restoreValue }
$curPlan | Invoke-CimMethod -MethodName Activate | Out-Null
$actionName = switch ($restoreValue) { 0 { "Do Nothing" } 1 { "Sleep" } 2 { "Hibernate" } 3 { "Shut Down" } default { "Unknown" } }
$source = if ($null -ne $script:userLidCloseAction) { "user preference" } else { "saved value" }
Write-Log "Lid close action restored to '$actionName' ($source)" "INFO"
$script:lidCloseManaged = $false
# Clear from runtime state
Clear-RuntimeState -LidCloseAction
return $true
}
return $false
}
}
catch {
Write-Log "Failed to manage lid close action: $_" "WARNING"
return $false
}
}
# Show Windows Toast Notification
function Show-Notification {
param(
[string]$Title,
[string]$Message,
[string]$Type = "Info"
)
try {
# Try WinRT toast notification (Windows 10/11)
[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
[void][Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
$appId = 'Microsoft.Windows.Explorer'
$escapedTitle = [System.Security.SecurityElement]::Escape($Title)
$escapedMessage = [System.Security.SecurityElement]::Escape($Message)
$toastXml = @"
<toast>
<visual>
<binding template="ToastGeneric">
<text>$escapedTitle</text>
<text>$escapedMessage</text>
</binding>
</visual>
<audio src="ms-winsoundevent:Notification.Default" />
</toast>
"@
$xml = [Windows.Data.Xml.Dom.XmlDocument]::new()
$xml.LoadXml($toastXml)
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId).Show($toast)
Write-Log "Notification shown: $Title" "INFO"
return
}
catch {
Write-Log "Toast notification failed, falling back to tray: $_" "WARNING"
}
# Fallback: System tray balloon notification
try {
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$notify = New-Object System.Windows.Forms.NotifyIcon
$notify.Icon = [System.Drawing.SystemIcons]::Information
$notify.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info
$notify.BalloonTipTitle = $Title
$notify.BalloonTipText = $Message
$notify.Visible = $true
# Register event to clean up after balloon is shown
$cleanup = Register-ObjectEvent -InputObject $notify -EventName BalloonTipClosed -Action {
try {
$Event.MessageData.Visible = $false
$Event.MessageData.Dispose()
}
catch {
Write-Error "Failed to dispose notification icon: $_"
}
Unregister-Event -SourceIdentifier $EventSubscriber.SourceIdentifier
Remove-Job -Id $EventSubscriber.Action.Id -Force
} -MessageData $notify
# Also set a timeout cleanup in case event doesn't fire
$timeout = Register-ObjectEvent -InputObject ([System.Timers.Timer]@{Interval = 6000; AutoReset = $false; Enabled = $true }) -EventName Elapsed -Action {
try {
$Event.MessageData.Visible = $false
$Event.MessageData.Dispose()
}
catch {
Write-Error "Failed to dispose notification icon on timeout: $_"
}
Unregister-Event -SourceIdentifier $EventSubscriber.SourceIdentifier
Remove-Job -Id $EventSubscriber.Action.Id -Force
} -MessageData $notify
$notify.ShowBalloonTip(5000)
Write-Log "Notification shown (tray): $Title" "INFO"
}
catch {
Write-Log "Could not show notification: $_" "WARNING"
}
}
# Check for updates (runs once per day)
function Check-ForUpdate {
param($config)
# Check if we should check for updates
$shouldCheck = $true
if (Test-Path $lastUpdateCheckFile) {
try {
$lastCheck = Get-Content $lastUpdateCheckFile | Get-Date
$timeSinceCheck = (Get-Date) - $lastCheck
if ($timeSinceCheck.TotalSeconds -lt $updateCheckInterval) {
$shouldCheck = $false
}
}
catch {
$shouldCheck = $true
}
}
if (-not $shouldCheck) {
return
}
# Check if update checks are enabled
if ($config.AutoUpdateCheck -eq $false) {
return
}
# Update the last check time
Get-Date | Set-Content $lastUpdateCheckFile -ErrorAction SilentlyContinue
try {
$currentVersion = $SCRIPT_VERSION
$updateUrl = "https://api.github.com/repos/Bananz0/eGPUae/releases/latest"
$releaseInfo = Invoke-RestMethod -Uri $updateUrl -ErrorAction Stop -TimeoutSec 5
$latestVersion = $releaseInfo.tag_name.TrimStart("v")
# Simple version comparison
$currentParts = $currentVersion.Split(".")
$latestParts = $latestVersion.Split(".")
$isNewer = $false
for ($i = 0; $i -lt 3; $i++) {
$curr = [int]$currentParts[$i]
$latest = [int]$latestParts[$i]
if ($latest -gt $curr) {
$isNewer = $true
break
}
elseif ($latest -lt $curr) {
break
}
}
if ($isNewer) {
Show-Notification -Title "eGPU Manager Update Available" `
-Message "Version $latestVersion is available (you have $currentVersion). Run the installer to update."
Write-Log "Update available: v$currentVersion -> v$latestVersion" "WARNING"
}
else {
Write-Log "Update check: Already on latest version (v$currentVersion)" "INFO"
}
}
catch {
Write-Log "Update check failed (will retry in 24h): $_" "INFO"
}
}
function Get-eGPUState {
param([string]$egpu_name)
$egpu = Get-PnpDevice | Where-Object { $_.FriendlyName -like "*$egpu_name*" }
if ($null -eq $egpu) {
return "absent"
}
try {
$problemCode = (Get-PnpDeviceProperty -InstanceId $egpu.InstanceId -KeyName "DEVPKEY_Device_ProblemCode" -ErrorAction Stop).Data
if ($egpu.Status -eq "OK") {
return "present-ok"
}
elseif ($egpu.Status -eq "Error") {
if ($problemCode -eq 45) {
return "absent"
}
else {
return "present-disabled"
}
}
else {
return "absent"
}
}
catch {
return "absent"
}
}
function Get-eGPUDevice {
param([string]$egpu_name)
return Get-PnpDevice | Where-Object { $_.FriendlyName -like "*$egpu_name*" }
}
function Enable-eGPU {
param(
[string]$egpu_name,
[int]$MaxRetries = 3
)
$egpu = Get-eGPUDevice -egpu_name $egpu_name
if ($null -eq $egpu) {
Write-Log "ERROR: eGPU device not found" "ERROR"
return $false
}
Write-Log "Device Details: Name=$($egpu.FriendlyName), Status=$($egpu.Status)" "INFO"
# Check if running as admin
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Log "WARNING: Script is NOT running as Administrator!" "ERROR"
return $false
}
$attempt = 0
while ($attempt -lt $MaxRetries) {
$attempt++
if ($attempt -gt 1) {
Write-Log "Retry attempt $attempt/$MaxRetries..." "WARNING"
}
try {
Write-Log "Using pnputil to enable device..." "INFO"
$enableResult = & pnputil /enable-device "$($egpu.InstanceId)" 2>&1
Write-Log "pnputil output: $enableResult" "INFO"
Start-Sleep -Seconds 2
$egpu = Get-eGPUDevice -egpu_name $egpu_name
if ($null -ne $egpu -and $egpu.Status -eq "OK") {
Write-Log "Device enabled successfully!" "SUCCESS"
return $true
}
$currentStatus = if ($null -ne $egpu) { $egpu.Status } else { "NULL" }
Write-Log "Enable attempted but status is: $currentStatus" "WARNING"
if ($attempt -lt $MaxRetries) {
Start-Sleep -Seconds 2
}
}
catch {
Write-Log "ERROR on attempt $attempt : $_" "ERROR"
if ($attempt -lt $MaxRetries) {
Start-Sleep -Seconds 2
}
}
}
return $false
}
# ===== NEW FEATURE FUNCTIONS =====
# Auto-launch configured apps when eGPU connects
function Start-AutoLaunchApps {
if ($script:autoLaunchApps.Count -eq 0) {
return
}
Write-Log "Auto-launching $($script:autoLaunchApps.Count) configured app(s)..." "INFO"
$script:launchedApps = @()
foreach ($appPath in $script:autoLaunchApps) {
if (Test-Path $appPath) {
try {
$process = Start-Process -FilePath $appPath -PassThru -ErrorAction SilentlyContinue
if ($process) {
$script:launchedApps += @{
Path = $appPath
ProcessName = $process.ProcessName
ProcessId = $process.Id
}
Write-Log " Launched: $appPath (PID: $($process.Id))" "SUCCESS"
}
}
catch {
Write-Log " Failed to launch: $appPath - $_" "WARNING"
}
}
else {
Write-Log " App not found: $appPath" "WARNING"
}
}
}
# Close apps that were auto-launched
function Stop-AutoLaunchedApps {
if (-not $script:closeLaunchersOnDisconnect -or $script:launchedApps.Count -eq 0) {
return
}
Write-Log "Closing $($script:launchedApps.Count) auto-launched app(s)..." "INFO"
foreach ($app in $script:launchedApps) {
try {
# Try to close by process name (more reliable than PID for launchers that spawn child processes)
$processes = Get-Process -Name $app.ProcessName -ErrorAction SilentlyContinue
if ($processes) {
$processes | ForEach-Object {
try {
$_.CloseMainWindow() | Out-Null
Start-Sleep -Milliseconds 500
if (-not $_.HasExited) {
$_ | Stop-Process -Force -ErrorAction SilentlyContinue
}
}
catch { }
}
Write-Log " Closed: $($app.ProcessName)" "SUCCESS"
}
}
catch {
Write-Log " Failed to close: $($app.ProcessName) - $_" "WARNING"
}
}
$script:launchedApps = @()
}
# Update connection statistics
function Update-ConnectionStatistics {
param(
[string]$EventType # "connect" or "disconnect"
)
if (-not $script:trackStatistics) {
return
}
try {
$config = Get-Content $configPath | ConvertFrom-Json
# Initialize statistics if not present
if (-not $config.PSObject.Properties.Name -contains 'Statistics') {
$config | Add-Member -NotePropertyName 'Statistics' -NotePropertyValue @{
TotalConnectCount = 0
TotalConnectedTimeMinutes = 0
LastConnected = $null
LastDisconnected = $null
}
}
$now = Get-Date
if ($EventType -eq "connect") {
$config.Statistics.TotalConnectCount++
$config.Statistics.LastConnected = $now.ToString("o")
$script:connectionStartTime = $now
Write-Log "Statistics: Connect #$($config.Statistics.TotalConnectCount)" "INFO"
}
elseif ($EventType -eq "disconnect") {
$config.Statistics.LastDisconnected = $now.ToString("o")
# Calculate session duration if we have a start time
if ($null -ne $script:connectionStartTime) {
$sessionMinutes = [math]::Round(($now - $script:connectionStartTime).TotalMinutes, 1)
$config.Statistics.TotalConnectedTimeMinutes += $sessionMinutes
Write-Log "Statistics: Session duration $sessionMinutes minutes, Total: $($config.Statistics.TotalConnectedTimeMinutes) minutes" "INFO"
$script:connectionStartTime = $null
}
}
$config | ConvertTo-Json -Depth 3 | Set-Content $configPath
}
catch {
Write-Log "Failed to update statistics: $_" "WARNING"
}
}
# Wrapper for Show-Notification that respects EnableNotifications config
function Send-Notification {
param(
[string]$Title,
[string]$Message,
[string]$Type = "Info"