-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript-corecycler.ps1
5421 lines (4294 loc) · 234 KB
/
script-corecycler.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.AUTHOR
sp00n
.VERSION
0.9.4.2
.DESCRIPTION
Sets the affinity of the selected stress test program process to only one core and cycles through
all the cores to test the stability of a Curve Optimizer setting
.LINK
https://github.com/sp00n/corecycler
.LICENSE
Creative Commons "CC BY-NC-SA"
https://creativecommons.org/licenses/by-nc-sa/4.0/
https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
.NOTES
Please excuse my amateurish code in this file, it's my first attempt at writing in PowerShell ._.
#>
# Global variables
$version = '0.9.4.2'
$startDate = Get-Date
$startDateTime = Get-Date -format yyyy-MM-dd_HH-mm-ss
$logFilePath = 'logs'
$logFilePathAbsolute = $PSScriptRoot + '\' + $logFilePath + '\'
$logFileName = 'CoreCycler_' + $startDateTime + '.log'
$logFileFullPath = $logFilePathAbsolute + $logFileName
$settings = $null
$selectedStressTestProgram = $null
$useAutomaticRuntimePerCore = $false
$windowProcess = $null
$windowProcessId = $null
$stressTestProcess = $null
$stressTestProcessId = $null
$processCounterPathId = $null
$processCounterPathTime = $null
$coresWithError = $null
$coresWithErrorsCounter = $null
$previousError = $null
$stressTestLogFileName = $null
$stressTestLogFilePath = $null
$prime95CPUSettings = $null
$FFTSizes = $null
$FFTMinMaxValues = $null
$minFFTSize = $null
$maxFFTSize = $null
$fftSubarray = $null
$lastFilePosition = 0
$lineCounter = 0
$newLogEntries = [System.Collections.ArrayList]::new()
$allLogEntries = [System.Collections.ArrayList]::new()
$allFFTLogEntries = [System.Collections.ArrayList]::new()
$cpuTestMode = $null
$coreTestOrderMode = $null
$coreTestOrderCustom = @()
$scriptExit = $false
$fatalError = $false
$otherError = $false
$previousFileSize = $null
$previousPassedFFTSize = $null
$previousPassedFFTEntry = $null
$isPrime95 = $false
$isAida64 = $false
$isYCruncher = $false
$cpuCheckIterations = 0
# Get the number of processor cores
$numberOfCores = (Get-WmiObject -Class Win32_Processor).NumberOfCores
# Input the desired CO starting values
Write-Host "Enter your base Curve Optimizer values for each of the $numberOfCores cores:" -ForegroundColor Green
# Define an array to store the values of $coresCO
$coresCO = @()
# Loop through each core and prompt for a valid user input
for ($i = 0; $i -lt $numberOfCores; $i++) {
do {
$value = Read-Host "Core $i"
if ($value -match '^[-]?\d+$' -and [int]$value -ge -30 -and [int]$value -le 30) {
$coresCO += [int]$value
} else {
Write-Host "ERROR: You must enter a value between -30 and 30" -ForegroundColor Red
}
} until ($value -match '^[-]?\d+$' -and [int]$value -ge -30 -and [int]$value -le 30)
}
# Apply the Curve Optimizer
$programPath = Join-Path $PSScriptRoot "tools\PBO2Tuner\PBO2Tuner.exe"
Start-Process -FilePath $programPath -ArgumentList $coresCO -Verb RunAs -WindowStyle Hidden
Write-Host "The following Curve Optimizer values have been applied: $coresCO" -ForegroundColor Green
# Parameters that are controllable by debug settings
$debugSettingsActive = $false
$disableCpuUtilizationCheckDefault = 0
$enableCpuFrequencyCheckDefault = 0
$tickIntervalDefault = 10
$delayFirstErrorCheckDefault = 0
$stressTestProgramPriorityDefault = 'High'
$stressTestProgramWindowToForegroundDefault = 0
$suspensionTimeDefault = 1000
$disableCpuUtilizationCheck = $disableCpuUtilizationCheckDefault
$enableCpuFrequencyCheck = $enableCpuFrequencyCheckDefault
$tickInterval = $tickIntervalDefault
$delayFirstErrorCheck = $delayFirstErrorCheckDefault
$stressTestProgramPriority = $stressTestProgramPriorityDefault
$stressTestProgramWindowToForeground = $stressTestProgramWindowToForegroundDefault
$suspensionTime = $suspensionTimeDefault
# Set the title
$host.UI.RawUI.WindowTitle = ('CoreCycler ' + $version + ' running')
# Stress test program executables and paths
# The window behaviours:
# 0 = Hide
# 1 = NormalFocus
# 2 = MinimizedFocus
# 3 = MaximizedFocus
# 4 = NormalNoFocus
# 6 = MinimizedNoFocus
$stressTestPrograms = @{
'prime95' = @{
'displayName' = 'Prime95'
'processName' = 'prime95'
'processNameExt' = 'exe'
'processNameForLoad' = 'prime95'
'processPath' = 'test_programs\p95'
'configName' = $null
'configFilePath' = $null
'absolutePath' = $null
'fullPathToExe' = $null
'command' = """%fullPathToExe%"" -t"
'windowBehaviour' = 0
'testModes' = @(
'SSE',
'AVX',
'AVX2',
'AVX512',
'CUSTOM'
)
'windowNames' = @(
'^Prime95 \- Torture Test$', # New in 30.7
'^Prime95 \- Self\-Test$',
'^Prime95 \- Not running$',
'^Prime95 \- Waiting for work$',
'^Prime95$'
)
}
'prime95_dev' = @{
'displayName' = 'Prime95 DEV'
'processName' = 'prime95_dev'
'processNameExt' = 'exe'
'processNameForLoad' = 'prime95_dev'
'processPath' = 'test_programs\p95_dev'
'configName' = $null
'configFilePath' = $null
'absolutePath' = $null
'fullPathToExe' = $null
'command' = """%fullPathToExe%"" -t"
'windowBehaviour' = 0
'testModes' = @(
'SSE',
'AVX',
'AVX2',
'AVX512',
'CUSTOM'
)
'windowNames' = @(
'^Prime95 \- Torture Test$', # New in 30.7
'^Prime95 \- Self\-Test$',
'^Prime95 \- Not running$',
'^Prime95 \- Waiting for work$',
'^Prime95$'
)
}
'aida64' = @{
'displayName' = 'Aida64'
'processName' = 'aida64'
'processNameExt' = 'exe'
'processNameForLoad' = 'aida_bench64.dll' # This needs to be with file extension
'processPath' = 'test_programs\aida64'
'configName' = $null
'configFilePath' = $null
'absolutePath' = $null
'fullPathToExe' = $null
'command' = """%fullPathToExe%"" /SAFEST /SILENT /SST %mode%"
'windowBehaviour' = 6
'testModes' = @(
'CACHE',
'CPU',
'FPU',
'RAM'
)
'windowNames' = @(
'^System Stability Test \- AIDA64*'
)
}
'ycruncher' = @{
'displayName' = "y-Cruncher"
'processName' = '' # Depends on the selected modeYCruncher
'processNameExt' = 'exe'
'processNameForLoad' = '' # Depends on the selected modeYCruncher
'processPath' = 'test_programs\y-cruncher\Binaries'
'configName' = 'stressTest.cfg'
'configFilePath' = $null
'absolutePath' = $null
'fullPathToExe' = $null
'command' = "cmd /C start /MIN ""y-Cruncher - %fileName%"" ""%fullPathToExe%"" priority:2 config ""%configFilePath%"""
'windowBehaviour' = 6
'testModes' = @(
'00-x86',
'04-P4P',
'05-A64 ~ Kasumi',
'08-NHM ~ Ushio',
'11-SNB ~ Hina',
'13-HSW ~ Airi',
'14-BDW ~ Kurumi',
'17-ZN1 ~ Yukina',
'19-ZN2 ~ Kagari',
'20-ZN3 ~ Yuzuki',
# The following settings seem to be designed for Intel CPUs and don't run on Ryzen CPUs
'11-BD1 ~ Miyu',
'17-SKX ~ Kotori',
'18-CNL ~ Shinoa',
# This setting is designed for Ryzen 7000 (Zen 4) CPUs and uses AVX-512
'22-ZN4 ~ Kizuna'
)
'windowNames' = @(
'' # Depends on the selected modeYCruncher
)
}
}
# Programs where both the main window and the stress test are the same process
$stressTestProgramsWithSameProcess = @(
'prime95', 'prime95_dev', 'ycruncher'
)
# Used to get around the localized counter names
$englishCounterNames = @(
'Process',
'ID Process',
'% Processor Time'
# Possible future use
#'Processor Information',
#'% Processor Performance',
#'% Processor Utility'
)
# This stores the Name:ID pairs of the english counter names
$counterNameIds = @{}
# This holds the localized counter names
# Stores the strings returned by Get-PerformanceCounterLocalName
$counterNames = @{
'Process' = ''
'ID Process' = ''
'% Processor Time' = ''
'FullName' = ''
'SearchString' = ''
'ReplaceString' = ''
# Possible future use
#'Processor Information' = ''
#'% Processor Performance' = ''
#'% Processor Utility' = ''
}
# The number of physical and logical cores
# This also includes hyperthreading resp. SMT (Simultaneous Multi-Threading)
# We currently only test the first core for each hyperthreaded "package",
# so e.g. only 12 cores for a 24 threaded Ryzen 5900x
# If you disable hyperthreading / SMT, both values should be the same
$processor = Get-CimInstance -ClassName Win32_Processor
$numLogicalCores = $($processor | Measure-Object -Property NumberOfLogicalProcessors -sum).Sum
$numPhysCores = $($processor | Measure-Object -Property NumberOfCores -sum).Sum
# Set the flag if Hyperthreading / SMT is enabled or not
$isHyperthreadingEnabled = ($numLogicalCores -gt $numPhysCores)
# Override the HashTable .ToString() method to generate readable output
# https://www.sapien.com/blog/2014/10/21/a-better-tostring-method-for-hash-tables/
Update-TypeData -TypeName System.Collections.HashTable `
-MemberType ScriptMethod `
-MemberName ToString `
-Value { `
$hashstr = "@{ "; `
$keys = $this.keys; `
foreach ($key in $keys) { `
$v = $this[$key]; `
if ($key -match "\s") { `
$hashstr += "`"$key`"" + "=" + "`"$v`"" + "; "; `
} `
else { `
$hashstr += $key + "=" + "`"$v`"" + "; "; `
} `
} `
$hashstr += "}"; `
return $hashstr; `
} `
-Force
# Prevent Sleep/Standby/Hibernation while the script is running
# https://stackoverflow.com/a/65162017/973927
$PowerUtilDefinition = @'
// Member variables.
static IntPtr _powerRequest;
static bool _mustResetDisplayRequestToo;
// P/Invoke function declarations.
[DllImport("kernel32.dll")]
static extern IntPtr PowerCreateRequest(ref POWER_REQUEST_CONTEXT Context);
[DllImport("kernel32.dll")]
static extern bool PowerSetRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);
[DllImport("kernel32.dll")]
static extern bool PowerClearRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern int CloseHandle(IntPtr hObject);
// Availablity Request Enumerations and Constants
enum PowerRequestType {
PowerRequestDisplayRequired = 0,
PowerRequestSystemRequired,
PowerRequestAwayModeRequired,
PowerRequestMaximum
}
const int POWER_REQUEST_CONTEXT_VERSION = 0;
const int POWER_REQUEST_CONTEXT_SIMPLE_STRING = 0x1;
// Availablity Request Structures
// Note: Windows defines the POWER_REQUEST_CONTEXT structure with an
// internal union of SimpleReasonString and Detailed information.
// To avoid runtime interop issues, this version of
// POWER_REQUEST_CONTEXT only supports SimpleReasonString.
// To use the detailed information,
// define the PowerCreateRequest function with the first
// parameter of type POWER_REQUEST_CONTEXT_DETAILED.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct POWER_REQUEST_CONTEXT {
public UInt32 Version;
public UInt32 Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string SimpleReasonString;
}
/// <summary>
/// Prevents the system from going to sleep, by default not including the display.
/// </summary>
/// <param name="enable">
/// True to turn on, False to turn off. Passing True must be paired with a later call passing False.
/// If you pass True repeatedly, subsequent invocations take no actions and ignore the parameters.
/// If you pass False, the remaining paramters are ignored.
// If you pass False without having passed True earlier, no action is performed.
//// </param>
/// <param name="includeDisplay">True to also keep the display awake; defaults to False.</param>
/// <param name="reasonString">
/// A string describing why the system is being kept awake; defaults to the current process' command line.
/// This will show in the output from `powercfg -requests` (requires elevation).
/// </param>
public static void StayAwake(bool enable, bool includeDisplay = false, string reasonString = null) {
if (enable) {
// Already enabled: quietly do nothing.
if (_powerRequest != IntPtr.Zero) { return; }
// Configure the reason string.
POWER_REQUEST_CONTEXT powerRequestContext;
powerRequestContext.Version = POWER_REQUEST_CONTEXT_VERSION;
powerRequestContext.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
powerRequestContext.SimpleReasonString = reasonString ?? System.Environment.CommandLine; // The reason for making the power request
// Create the request (returns a handle).
_powerRequest = PowerCreateRequest(ref powerRequestContext);
// Set the request(s).
PowerSetRequest(_powerRequest, PowerRequestType.PowerRequestSystemRequired);
if (includeDisplay) {
PowerSetRequest(_powerRequest, PowerRequestType.PowerRequestDisplayRequired);
}
_mustResetDisplayRequestToo = includeDisplay;
}
else {
// Not previously enabled: quietly do nothing.
if (_powerRequest == IntPtr.Zero) {
return;
}
// Clear the request
PowerClearRequest(_powerRequest, PowerRequestType.PowerRequestSystemRequired);
if (_mustResetDisplayRequestToo) {
PowerClearRequest(_powerRequest, PowerRequestType.PowerRequestDisplayRequired);
}
CloseHandle(_powerRequest);
_powerRequest = IntPtr.Zero;
}
}
// Overload that allows passing a reason string while defaulting to keeping the display awake too.
public static void StayAwake(bool enable, string reasonString) {
StayAwake(enable, false, reasonString);
}
'@
# Add code definitions so that we can close a window even if it's minimized to the tray
# The regular PowerShell way unfortunetely doesn't work in this case
# The definition to get the main window handle even if the process is minimized to the tray
$GetWindowsDefinition = @'
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace GetWindows {
public class WinStruct {
public string WinTitle {get; set; }
public int MainWindowHandle { get; set; }
public string ProcessPath { get; set; }
public int ProcessId { get; set; }
}
public class Main {
private static int PROCESS_QUERY_INFORMATION = (0x00000400);
private static int PROCESS_VM_READ = (0x00000010);
private delegate bool CallBackPtr(int hwnd, int lParam);
private static CallBackPtr callBackPtr = Callback;
private static List<WinStruct> _WinStructList = new List<WinStruct>();
// Get all windows
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam);
// Get the window title
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
// Get the process id for the window
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
// Open a process
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
// Get the process path for a window
[DllImport("psapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, StringBuilder lpFilename, int nSize);
private static bool Callback(int hWnd, int lparam) {
int processId;
StringBuilder sb1 = new StringBuilder(1024);
StringBuilder sb2 = new StringBuilder(1024);
int getIdResult = GetWindowThreadProcessId((IntPtr)hWnd, out processId);
int getWindowTextResult = GetWindowText((IntPtr)hWnd, sb1, 1024);
int openProcessResult = OpenProcess((PROCESS_QUERY_INFORMATION+PROCESS_VM_READ), true, processId);
int getFileNameResult = GetModuleFileNameEx((IntPtr)openProcessResult, IntPtr.Zero, sb2, 1024);
_WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb1.ToString(), ProcessPath = sb2.ToString(), ProcessId = processId });
return true;
}
public static List<WinStruct> GetWindows() {
_WinStructList = new List<WinStruct>();
EnumWindows(callBackPtr, IntPtr.Zero);
return _WinStructList;
}
}
}
'@
# The definition to send a message to a process
$SendMessageDefinition = @'
using System;
using System.Runtime.InteropServices;
public static class SendMessageClass {
// Values for Msg
public static uint WM_SETFOCUS = 0x0007; // Set focus command
public static uint WM_CLOSE = 0x0010; // Close command
public static uint WM_SYSCOMMAND = 0x0112; // Initiate a system command (minimize, maximize, etc)
public static uint WM_SYSCHAR = 0x0106; // Send a system character. This is a bit confusing
public static uint WM_SYSKEYDOWN = 0x0104; // System key down
public static uint WM_SYSKEYUP = 0x0105; // System key up
public static uint KEY_DOWN = 0x0100; // Key down
public static uint KEY_UP = 0x0101; // Key up
public static uint VM_CHAR = 0x0102; // Send a keyboard character (see below)
public static uint LBUTTONDOWN = 0x0201; // Left mouse button down
public static uint LBUTTONUP = 0x0202; // Left mouse button up
// This needs to be send to a button child "window" handle
public static uint BM_CLICK = 0x00F5; // Mouse click on a button
// Values for wParam
public static uint KEY_A = 0x0041; // A
public static uint KEY_D = 0x0044; // D
public static uint KEY_E = 0x0045; // E
public static uint KEY_S = 0x0053; // S
public static uint KEY_T = 0x0054; // T
public static uint KEY_MENU = 0x0012; // ALT Key
// To be used in conjunction with WM_SYSCOMMAND
public static uint SC_CLOSE = 0xF060; // Close command
public static uint SC_MINIMIZE = 0xF020; // Minimize command
public static uint SC_RESTORE = 0xF120; // Restore window command
// Values for calculating lParam
public static uint MAPVK_VK_TO_VSC = 0x0000;
public static uint MAPVK_VSC_TO_VK = 0x0001;
public static uint MAPVK_VK_TO_CHAR = 0x0002;
public static uint MAPVK_VSC_TO_VK_EX = 0x0003;
public static uint MAPVK_VK_TO_VSC_EX = 0x0004;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern uint MapVirtualKey(uint uCode, uint uMapType);
public static uint GetLParam(Int16 repeatCount, uint key, byte extended, byte contextCode, byte previousState, byte transitionState) {
var lParam = (uint) repeatCount;
uint scanCode = MapVirtualKey(key, MAPVK_VK_TO_CHAR);
lParam += scanCode*0x10000;
lParam += (uint) ((extended)*0x1000000);
lParam += (uint) ((contextCode*2)*0x10000000);
lParam += (uint) ((previousState*4)*0x10000000);
lParam += (uint) ((transitionState*8)*0x10000000);
return lParam;
}
// SendMessage. Seems to return always 0
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
// PostMessage. Seems to return always 1
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr PostMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
'@
# Make the external code definitions available to PowerShell
Add-Type -ErrorAction Stop -Name PowerUtil -Namespace Windows -MemberDefinition $PowerUtilDefinition
Add-Type -TypeDefinition $GetWindowsDefinition
$SendMessage = Add-Type -TypeDefinition $SendMessageDefinition -PassThru
# Also make VisualBasic available
Add-Type -Assembly Microsoft.VisualBasic
<#
.DESCRIPTION
Write a message to the screen and to the log file
.PARAMETER text
[String] The text to output
.OUTPUTS
void
#>
function Write-Text {
param(
[Parameter(Mandatory=$true)]
$text
)
Write-Host $text
Add-Content $logFileFullPath ($text)
}
<#
.DESCRIPTION
Write an error message to the screen and to the log file
.PARAMETER errorArray
[Array] An array with the text entries to output
.OUTPUTS
[Void]
#>
function Write-ErrorText {
param(
[Parameter(Mandatory=$true)]
$errorArray
)
foreach ($entry in $errorArray) {
$lines = @()
$lines += $entry.Exception.Message
$lines += $entry.InvocationInfo.PositionMessage
$lines += (' + CategoryInfo : ' + $entry.CategoryInfo.Category + ': (' + $entry.CategoryInfo.TargetName + ':' + $entry.CategoryInfo.TargetType + ') [' + $entry.CategoryInfo.Activity + '], ' + $entry.CategoryInfo.Reason)
$lines += (' + FullyQualifiedErrorId : ' + $entry.FullyQualifiedErrorId)
$string = $lines | Out-String
Write-Host $string -ForegroundColor Red
Add-Content $logFileFullPath ($string)
}
}
<#
.DESCRIPTION
Write a message to the screen with a specific color and to the log file
.PARAMETER text
[String] The text to output
.PARAMETER foregroundColor
[String] The foreground color
.PARAMETER backgroundColor
[String] (optional) The background color
.OUTPUTS
[Void]
#>
function Write-ColorText {
param(
[Parameter(Mandatory=$true)]
$text,
[Parameter(Mandatory=$true)]
$foregroundColor,
[Parameter(Mandatory=$false)]
$backgroundColor
)
# -ForegroundColor <ConsoleColor>
# -BackgroundColor <ConsoleColor>
# Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White
if ($backgroundColor) {
Write-Host $text -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
}
else {
Write-Host $text -ForegroundColor $foregroundColor
}
Add-Content $logFileFullPath ($text)
}
<#
.DESCRIPTION
Write a verbose message to the screen and to the log file
Verbose output
.PARAMETER text
[String] The text to output
.OUTPUTS
[Void]
#>
function Write-Verbose {
param(
[Parameter(Mandatory=$true)]
$text
)
if ($settings.Logging.logLevel -ge 1) {
if ($settings.Logging.logLevel -ge 3) {
Write-Host(''.PadLeft(11, ' ') + ' + ' + $text) -ForegroundColor 'DarkGray'
}
Add-Content $logFileFullPath (''.PadLeft(11, ' ') + ' + ' + $text)
}
}
<#
.DESCRIPTION
Write a debug message to the screen and to the log file
Debug output
.PARAMETER text
[String] The text to output
.OUTPUTS
[Void]
#>
function Write-Debug {
param(
[Parameter(Mandatory=$true)]
$text
)
if ($settings.Logging.logLevel -ge 2) {
if ($settings.Logging.logLevel -ge 4) {
Write-Host(''.PadLeft(11, ' ') + ' + ' + $text) -ForegroundColor 'DarkGray'
}
Add-Content $logFileFullPath (''.PadLeft(11, ' ') + ' + ' + $text)
}
}
<#
.DESCRIPTION
Exit the script
.PARAMETER text
[String] (optional) The text to display
.OUTPUTS
[Void]
#>
function Exit-Script {
param(
[Parameter(Mandatory=$false)]
$text
)
$Script:scriptExit = $true
if ($text) {
Write-Text($text)
}
exit
}
<#
.DESCRIPTION
Throw a fatal error and exit the script
.PARAMETER text
[String] (optional) The text to display
.OUTPUTS
[Void]
#>
function Exit-WithFatalError {
param(
[Parameter(Mandatory=$false)]
$text
)
$Script:fatalError = $true
if ($text) {
Write-ColorText('FATAL ERROR: ' + $text) Red
}
Write-Host
Write-Host
Write-Host 'You can find more information in the log file:' -ForegroundColor Yellow
Write-Host $logFileFullPath -ForegroundColor Cyan
Write-Host 'When reporting this error, please provide this log file.' -ForegroundColor Yellow
Read-Host -Prompt 'Press Enter to exit'
exit
}
<#
.DESCRIPTION
Final summary when exiting the script
.PARAMETER
[Void]
.OUTPUTS
[String]
#>
function Show-FinalSummary {
# Get the total runtime
$endDate = Get-Date
$difference = New-TimeSpan -Start $startDate -End $endDate
$runtimeArray = @()
if ( $difference.Days -gt 0 ) {
$runtimeArray += ($difference.Days.ToString() + ' days')
}
if ( $difference.Hours -gt 0 ) {
$runtimeArray += ($difference.Hours.ToString().PadLeft(2, '0') + ' hours')
}
if ( $difference.Minutes -gt 0 ) {
$runtimeArray += ($difference.Minutes.ToString().PadLeft(2, '0') + ' minutes')
}
if ( $difference.Seconds -gt 0 ) {
$runtimeArray += ($difference.Seconds.ToString().PadLeft(2, '0') + ' seconds')
}
$runTimeString = $runtimeArray -Join ', '
Write-ColorText('') Green
Write-ColorText('---------------------') Green
Write-ColorText('------ Summary ------') Green
Write-ColorText('---------------------') Green
Write-ColorText('The script ran for ' + $runTimeString) Cyan
# Display the cores with error
if ( $coresWithError.Length -gt 0 ) {
$coresWithErrorString = (($coresWithError | sort) -Join ', ')
Write-ColorText('The following cores have thrown an error: ') Cyan
Write-ColorText(' - ' + $coresWithErrorString) Cyan
}
else {
Write-ColorText('No core has thrown an error') Cyan
}
}
<#
.DESCRIPTION
Get the localized counter name
Yes, they're localized. Way to go Microsoft!
.PARAMETER ID
[UInt32] The id of the counter name. See the link above on how to get the IDs
.PARAMETER ComputerName
[String] The name of the computer to query. Defaults to the current computer
.OUTPUTS
[String] The localized name
.LINK
https://www.powershellmagazine.com/2013/07/19/querying-performance-counters-from-powershell/
#>
function Get-PerformanceCounterLocalName {
param (
[UInt32]
$ID,
$ComputerName = $env:COMPUTERNAME
)
$code = '[DllImport("pdh.dll", SetLastError=true, CharSet=CharSet.Unicode)] '
$code += 'public static extern UInt32 PdhLookupPerfNameByIndex(string szMachineName, uint dwNameIndex, System.Text.StringBuilder szNameBuffer, ref uint pcchNameBufferSize);'
$Buffer = New-Object System.Text.StringBuilder(1024)
[UInt32] $BufferSize = $Buffer.Capacity
$type = Add-Type -MemberDefinition $code -PassThru -Name PerfCounter -Namespace Utility
$queryResult = $type::PdhLookupPerfNameByIndex($ComputerName, $ID, $Buffer, [Ref] $BufferSize)
# 0 = ERROR_SUCCESS
if ( $queryResult -eq 0 ) {
$Buffer.ToString().Substring(0, $BufferSize-1)
}
else {
Throw 'Get-PerformanceCounterLocalName : Unable to retrieve localized name. Check computer name and performance counter ID.'
}
}
<#
.DESCRIPTION
This is used to get the Performance Counter IDs, which will be used to get the localized names
.PARAMETER englishCounterNames
[Array] An array with the english names of the counters
.OUTPUTS
[HashTable] A hashtable with Name:ID pairs of the counters
#>
function Get-PerformanceCounterIDs {
param (
[Parameter(Mandatory=$true)]
[Array] $englishCounterNames
)
$key = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009'
$allCounters = (Get-ItemProperty -Path $key -Name Counter).Counter
$numCounters = $allCounters.Count
$countersHash = @{}
# The string contains two-line pairs
# The first line is the ID
# The second line is the name
# TODO: Maybe make it more robust by actually checking the order of the ID and Text
for ($i = 0; $i -lt $numCounters; $i += 2) {
$counterId = [Int] $allCounters[$i]
$counterName = [String] $allCounters[$i+1]
if ($englishCounterNames -contains $counterName -and !$countersHash.ContainsKey($counterName)) {
$countersHash[$counterName] = $counterId
}
}
return $countersHash
}
##############################################################################
##
## Invoke-WindowsApi.ps1
##
## http://www.leeholmes.com/blog/2007/10/02/managing-ini-files-with-powershell/
##
## From PowerShell Cookbook (O’Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Invoke a native Windows API call that takes and returns simple data types.
##
## ie:
##
## ## Prepare the parameter types and parameters for the
## CreateHardLink function
## $parameterTypes = [String], [String], [IntPtr]
## $parameters = [String] $filename, [String] $existingFilename, [IntPtr]::Zero
##
## ## Call the CreateHardLink method in the Kernel32 DLL
## $result = Invoke-WindowsApi "kernel32" ([Bool]) "CreateHardLink" `
## $parameterTypes $parameters
##
##############################################################################
# Unfortunately this introduces a memory leak when called multiple times in a row
##############################################################################
function Invoke-WindowsApi {
param(
[String] $dllName,
[Type] $returnType,
[String] $methodName,
[Type[]] $parameterTypes,
[Object[]] $parameters
)
## Begin to build the dynamic assembly
$domain = [AppDomain]::CurrentDomain
$name = New-Object Reflection.AssemblyName 'PInvokeAssembly'
# TODO: This is potentially huge memory hog!
# Only really noticable when using Aida64 though
# Maybe this? https://stackoverflow.com/questions/2503645/reflect-emit-dynamic-type-memory-blowup
$assembly = $domain.DefineDynamicAssembly($name, 'Run')
$module = $assembly.DefineDynamicModule('PInvokeModule')
$type = $module.DefineType('PInvokeType', 'Public,BeforeFieldInit')
## Go through all of the parameters passed to us. As we do this,
## we clone the user's inputs into another array that we will use for
## the P/Invoke call.
$inputParameters = @()
$refParameters = @()
for ($counter = 1; $counter -le $parameterTypes.Length; $counter++) {
## If an item is a PSReference, then the user
## wants an [Out] parameter.
if ($parameterTypes[$counter - 1] -eq [Ref]) {
## Remember which parameters are used for [Out] parameters
$refParameters += $counter
## On the cloned array, we replace the PSReference type with the
## .Net reference type that represents the value of the PSReference,
## and the value with the value held by the PSReference.
$parameterTypes[$counter - 1] = $parameters[$counter - 1].Value.GetType().MakeByRefType()
$inputParameters += $parameters[$counter - 1].Value
}
else {
## Otherwise, just add their actual parameter to the
## input array.
$inputParameters += $parameters[$counter - 1]
}
}
## Define the actual P/Invoke method, adding the [Out]
## attribute for any parameters that were originally [Ref]
## parameters.
$method = $type.DefineMethod($methodName, 'Public,HideBySig,Static,PinvokeImpl', $returnType, $parameterTypes)
foreach ($refParameter in $refParameters) {
[Void] $method.DefineParameter($refParameter, 'Out', $null)
}
## Apply the P/Invoke constructor
$ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
$attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName
$method.SetCustomAttribute($attr)
## Create the temporary type, and invoke the method.
$realType = $type.CreateType()
$realType.InvokeMember($methodName, 'Public,Static,InvokeMethod', $null, $null, $inputParameters)
## Finally, go through all of the reference parameters, and update the
## values of the PSReference objects that the user passed in.
foreach ($refParameter in $refParameters) {
$parameters[$refParameter - 1].Value = $inputParameters[$refParameter - 1]
}
# Cleanup
# But it doesn't help
# So this might be an issue with .NET / C# itself?
# For example this? https://stackoverflow.com/questions/2503645/reflect-emit-dynamic-type-memory-blowup