-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathD2rSPLoader.ps1
2525 lines (2514 loc) · 126 KB
/
D2rSPLoader.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: Shupershuff
Usage:
Happy for you to make any modifications to this script for your own needs providing:
- Any variants of this script are never sold.
- Any variants of this script published online should always be open source.
Purpose:
Script is mainly orientated around tracking character playtime and total game time for single player.
Script will track character details from CSV.
Instructions: See GitHub readme https://github.com/shupershuff/D2rSPLoader
Changes since 1.1.0 (next version edits):
- Changed Skipped backup message.
- Removed "multibox" from welcome banner.
- Fixed typo in config.xml.
- Script now gets 'Saved Games' folder path from registry rather than assuming it's in 'C:\Users\Username\Saved Games'.
- Error handling for missing files where user is using '-direct -txt' launch arguments.
- Fixed a few issues with mod handling for disable/enable videos.
- Made it so if mods are being used, the mods folder that contains characters and settings is also backed up.
1.0.0+ to do list
Couldn't write :) in release notes without it adding a new line, some minor issue with formatfunction regex
Fix whatever I broke or poorly implemented in the last update :)
#>
$CurrentVersion = "1.1.0"
###########################################################################################################################################
# Script itself
###########################################################################################################################################
$host.ui.RawUI.WindowTitle = "Diablo 2 Resurrected: Single Player Loader"
#run script as admin
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){ Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $ScriptArguments" -Verb RunAs;exit }
#DebugMode
#$DebugMode = $True # Uncomment to enable
if ($DebugMode -eq $True){
$DebugPreference = "Continue"
$VerbosePreference = "Continue"
}
#set window size
[console]::WindowWidth=77; #script has been designed around this width. Adjust at your own peril.
$WindowHeight=50 #Can be adjusted to preference, but not less than 42
do {
Try{
[console]::WindowHeight = $WindowHeight;
$HeightSuccessfullySet = $True
}
Catch {
$WindowHeight --
}
} Until ($HeightSuccessfullySet -eq $True)
[console]::BufferWidth=[console]::WindowWidth
#set misc vars
$Script:X = [char]0x1b #escape character for ANSI text colors
$ProgressPreference = "SilentlyContinue"
$Script:WorkingDirectory = ((Get-ChildItem -Path $PSScriptRoot)[0].fullname).substring(0,((Get-ChildItem -Path $PSScriptRoot)[0].fullname).lastindexof('\')) #Set Current Directory path.
$Script:StartTime = Get-Date #Used for elapsed time. Is reset when script refreshes.
$Script:LastBackup = $Script:StartTime.addminutes(-60)
$Script:MOO = "%%%"
$Script:JobIDs = @()
$MenuRefreshRate = 30 #How often the script refreshes in seconds. This should be set to 30, don't change this please.
$Script:ScriptFileName = Split-Path $MyInvocation.MyCommand.Path -Leaf #find the filename of the script in case a user renames it.
$Script:SessionTimer = 0 #set initial session timer to avoid errors in info menu.
$Script:NotificationHasBeenChecked = $False
#Baseline of acceptable characters for ReadKey functions. Used to prevents receiving inputs from folk who are alt tabbing etc.
$Script:AllowedKeyList = @(48,49,50,51,52,53,54,55,56,57) #0 to 9
$Script:AllowedKeyList += @(96,97,98,99,100,101,102,103,104,105) #0 to 9 on numpad
$Script:AllowedKeyList += @(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) # A to Z
$Script:MenuOptions = @(65,66,67,68,71,73,74,79,82,83,84,88) #a, b, c, d, g, i, j, o, r, s, t and x. Used to detect singular valid entries where script can have two characters entered.
$EnterKey = 13
try {
$Script:WindowsSavedGameLocation = (Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -name "{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}")."{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}" + "\Diablo II Resurrected\" #Get Saved Games folder from registry rather than assume it's in C:\Users\Username\Saved Games
}
Catch {
$Script:WindowsSavedGameLocation = ("C:\Users\" + $Env:UserName + "\Saved Games\Diablo II Resurrected\")
}
$Script:CharacterSavePath = $Script:WindowsSavedGameLocation
$Script:SettingsProfilePath = $Script:WindowsSavedGameLocation
Function RemoveMaximiseButton { # I'm removing the maximise button on the script as sometimes I misclick maximise instead of minimise and it annoys me. Copied this straight out of ChatGPT lol.
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowAPI {
public const int GWL_STYLE = -16;
public const int WS_MAXIMIZEBOX = 0x10000;
public const int WS_THICKFRAME = 0x40000; // Window has a sizing border
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
}
"@
# Get the handle for the current window (PowerShell window)
$hWnd = [WindowAPI]::GetForegroundWindow()
# Get the current window style
$style = [WindowAPI]::GetWindowLong($hWnd, [WindowAPI]::GWL_STYLE)
# Disable the maximize button by removing the WS_MAXIMIZEBOX style. Also disable resizing the width.
$newStyle = $style -band -bnot ([WindowAPI]::WS_MAXIMIZEBOX -bor [WindowAPI]::WS_THICKFRAME)
[WindowAPI]::SetWindowLong($hWnd, [WindowAPI]::GWL_STYLE, $newStyle) | out-null
}
Function ReadKey([string]$message=$Null,[bool]$NoOutput,[bool]$AllowAllKeys){#used to receive user input
$Script:key = $Null
$Host.UI.RawUI.FlushInputBuffer()
if (![string]::IsNullOrEmpty($message)){
Write-Host -NoNewLine $message
}
$AllowedKeyList = $Script:AllowedKeyList + @(13,27) #Add Enter & Escape to the allowedkeylist as acceptable inputs.
while ($Null -eq $key){
if ($Host.UI.RawUI.KeyAvailable){
$key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
if ($True -ne $AllowAllKeys){
if ($key_.KeyDown -and $key_.VirtualKeyCode -in $AllowedKeyList){
$key = $key_
}
}
else {
if ($key_.KeyDown){
$script:key = $key_
}
}
}
else {
Start-Sleep -m 200 # Milliseconds
}
}
if ($key_.VirtualKeyCode -ne $EnterKey -and -not ($Null -eq $key) -and [bool]$NoOutput -ne $true){
Write-Host ("$X[38;2;255;165;000;22m" + "$($key.Character)" + "$X[0m") -NoNewLine
}
if (![string]::IsNullOrEmpty($message)){
Write-Host "" # newline
}
return $(
if ($Null -eq $key -or $key.VirtualKeyCode -eq $EnterKey){
""
}
ElseIf ($key.VirtualKeyCode -eq 27){ #if key pressed was escape
"Esc"
}
else {
$key.Character
}
)
}
Function ReadKeyTimeout([string]$message=$Null, [int]$timeOutSeconds=0, [string]$Default=$Null, [object[]]$AdditionalAllowedKeys = $null, [bool]$TwoDigitAcctSelection = $False){
$Script:key = $Null
$inputString = ""
$Host.UI.RawUI.FlushInputBuffer()
if (![string]::IsNullOrEmpty($message)){
Write-Host -NoNewLine $message
}
$Counter = $timeOutSeconds * 1000 / 250
$AllowedKeyList = $Script:AllowedKeyList + $AdditionalAllowedKeys #Add any other specified allowed key inputs (eg Enter).
while ($Null -eq $key -and ($timeOutSeconds -eq 0 -or $Counter-- -gt 0)){
if ($TwoDigitAcctSelection -eq $True -and $inputString.length -ge 1){
$AllowedKeyList = $AllowedKeyList + 13 + 8 # Allow enter and backspace to be used if 1 character has been typed.
}
if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable){
$key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
if ($key_.KeyDown -and $key_.VirtualKeyCode -in $AllowedKeyList){
if ($key_.VirtualKeyCode -eq [System.ConsoleKey]::Backspace){
$Counter = $timeOutSeconds * 1000 / 250 #reset counter
if ($inputString.Length -gt 0){
$inputString = $inputString.Substring(0, $inputString.Length - 1) #remove last added character/number from variable
# Clear the last character from the console
$Host.UI.RawUI.CursorPosition = @{
X = [Math]::Max($Host.UI.RawUI.CursorPosition.X - 1, 0)
Y = $Host.UI.RawUI.CursorPosition.Y
}
Write-Host -NoNewLine " " #-ForegroundColor Black
$Host.UI.RawUI.CursorPosition = @{
X = [Math]::Max($Host.UI.RawUI.CursorPosition.X - 1, 0)
Y = $Host.UI.RawUI.CursorPosition.Y
}
}
}
ElseIf ($TwoDigitAcctSelection -eq $True -and $key_.VirtualKeyCode -notin $Script:MenuOptions + 27){
$Counter = $timeOutSeconds * 1000 / 250 #reset counter
if ($key_.VirtualKeyCode -eq $EnterKey -or $key_.VirtualKeyCode -eq 27){
break
}
$inputString += $key_.Character
Write-Host ("$X[38;2;255;165;000;22m" + $key_.Character + "$X[0m") -nonewline
if ($inputString.length -eq 2){#if 2 characters have been entered
break
}
}
Else {
$script:key = $key_
$inputString = $key_.Character
}
}
}
else {
Start-Sleep -m 250 # Milliseconds
}
}
if ($Counter -le 0){
if ($InputString.Length -gt 0){# if it timed out, revert to no input if one character was entered.
$InputString = "" #remove last added character/number from variable
}
}
if ($TwoDigitAcctSelection -eq $False -or ($TwoDigitAcctSelection -eq $True -and $key_.VirtualKeyCode -in $Script:MenuOptions)){
Write-Host ("$X[38;2;255;165;000;22m" + "$inputString" + "$X[0m")
}
if (![string]::IsNullOrEmpty($message) -or $TwoDigitAcctSelection -eq $True){
Write-Host "" # newline
}
Write-Host #prevent follow up text from ending up on the same line.
return $(
If ($key.VirtualKeyCode -eq $EnterKey -and $EnterKey -in $AllowedKeyList){
""
}
ElseIf ($key.VirtualKeyCode -eq 27){ #if key pressed was escape
"Esc"
}
ElseIf ($inputString.Length -eq 0){
$Default
}
else {
$inputString
}
)
}
Function PressTheAnyKey {#Used instead of Pause so folk can hit any key to continue
Write-Host " Press any key to continue..." -nonewline
readkey -NoOutput $True -AllowAllKeys $True | out-null
Write-Host
}
Function PressTheAnyKeyToExit {#Used instead of Pause so folk can hit any key to exit
Write-Host " Press Any key to exit..." -nonewline
readkey -NoOutput $True -AllowAllKeys $True | out-null
remove-job * -force
Exit
}
Function Red {
process { Write-Host $_ -ForegroundColor Red }
}
Function Yellow {
process { Write-Host $_ -ForegroundColor Yellow }
}
Function Green {
process { Write-Host $_ -ForegroundColor Green }
}
Function NormalText {
process { Write-Host $_ }
}
Function FormatFunction { # Used to get long lines formatted nicely within the CLI. Possibly the most difficult thing I've created in this script. Hooray for Regex!
param (
[string] $Text,
[int] $Indents,
[int] $SubsequentLineIndents,
[switch] $IsError,
[switch] $IsWarning,
[switch] $IsSuccess
)
if ($IsError -eq $True){
$Colour = "Red"
}
ElseIf ($IsWarning -eq $True){
$Colour = "Yellow"
}
ElseIf ($IsSuccess -eq $True){
$Colour = "Green"
}
Else {
$Colour = "NormalText"
}
$MaxLineLength = 76
If ($Indents -ge 1){
while ($Indents -gt 0){
$Indent += " "
$Indents --
}
}
If ($SubsequentLineIndents -ge 1){
while ($SubsequentLineIndents -gt 0){
$SubsequentLineIndent += " "
$SubsequentLineIndents --
}
}
$Text -split "`n" | ForEach-Object {
$Line = " " + $Indent + $_
$SecondLineDeltaIndent = ""
if ($Line -match '^[\s]*-'){ #For any line starting with any preceding spaces and a dash.
$SecondLineDeltaIndent = " "
}
if ($Line -match '^[\s]*\d+\.\s'){ #For any line starting with any preceding spaces, a number, a '.' and a space. Eg "1. blah".
$SecondLineDeltaIndent = " "
}
Function Formatter ([string]$line){
$pattern = "[\e]?[\[]?[`"-,`.!']?\b[\w\-,'`"]+(\S*)" # Regular expression pattern to find the last word including any trailing non-space characters. Also looks to include any preceding special characters or ANSI escape character.
$WordMatches = [regex]::Matches($Line, $pattern) # Find all matches of the pattern in the string
# Initialize variables to track the match with the highest index
$highestIndex = -1
$SelectedMatch = $Null
$PatternLengthCount = 0
$ANSIPatterns = "\x1b\[38;\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3}m","\x1b\[0m","\x1b\[4m"
ForEach ($WordMatch in $WordMatches){# Iterate through each match (match being a block of characters, ie each word).
ForEach ($ANSIPattern in $ANSIPatterns){ #iterate through each possible ANSI pattern to find any text that might have ANSI formatting.
$ANSIMatches = $WordMatch.value | Select-String -Pattern $ANSIPattern -AllMatches
ForEach ($ANSIMatch in $ANSIMatches){
$Script:ANSIUsed = $True
$PatternLengthCount = $PatternLengthCount + (($ANSIMatch.matches | ForEach-Object {$_.Value}) -join "").length #Calculate how many characters in the text are ANSI formatting characters and thus won't be displayed on screen, to prevent skewing word count.
}
}
$matchIndex = $WordMatch.Index
$matchLength = $WordMatch.Length
$matchEndIndex = $matchIndex + $matchLength - 1
if ($matchEndIndex -lt ($MaxLineLength + $PatternLengthCount)){# Check if the match ends within the first $MaxLineLength characters
if ($matchIndex -gt $highestIndex){# Check if this match has a higher index than the current highest
$highestIndex = $matchIndex # This word has a higher index and is the winner thus far.
$SelectedMatch = $WordMatch
$lastspaceindex = $SelectedMatch.Index + $SelectedMatch.Length - 1 #Find the index (the place in the string) where the last word can be used without overflowing the screen.
}
}
}
try {
$script:chunk = $Line.Substring(0, $lastSpaceIndex + 1) #Chunk of text to print to screen. Uses all words from the start of $line up until $lastspaceindex so that only text that fits on a single line is printed. Prevents words being cut in half and prevents loss of indenting.
}
catch {
$script:chunk = $Line.Substring(0, [Math]::Min(($MaxLineLength), ($Line.Length))) #If the above fails for whatever reason. Can't exactly remember why I put this in here but leaving it in to be safe LOL.
}
}
Formatter $Line
if ($Script:ANSIUsed -eq $True){ #if fancy pants coloured text (ANSI) is used, write out the first line. Check if ANSI was used in any overflow lines.
do {
$Script:ANSIUsed = $False
Write-Output $Chunk | out-host #have to use out-host due to pipeline shenanigans and at this point was too lazy to do things properly :)
$Line = " " + $SubsequentLineIndent + $Indent + $Line.Substring($chunk.Length).trimstart() #$Line is equal to $Line but without the text that's already been outputted.
Formatter $Line
} until ($Script:ANSIUsed -eq $False)
if ($Chunk -ne " " -and $Chunk.lenth -ne 0){#print any remaining text.
Write-Output $Chunk | out-host
}
}
Else { #if line has no ANSI formatting.
Write-Output $Chunk | &$Colour
}
$Line = $Line.Substring($chunk.Length).trimstart() #remove the string that's been printed on screen from variable.
if ($Line.length -gt 0){ # I see you're reading my comment. How thorough of you! This whole function was an absolute mindf#$! to come up with and took probably 30 hours of trial, error and rage (in ascending order of frequency). Odd how the most boring of functions can take up the most time :)
Write-Output ($Line -replace "(.{1,$($MaxLineLength - $($Indent.length) - $($SubsequentLineIndent.length) -1 - $($SecondLineDeltaIndent.length))})(\s+|$)", " $SubsequentLineIndent$SecondLineDeltaIndent$Indent`$1`n").trimend() | &$Colour
}
}
}
Function CommaSeparatedList {
param (
[object] $Values,
[switch] $NoOr,
[switch] $AndText
)
ForEach ($Value in $Values){ #write out each account option, comma separated but show each option in orange writing. Essentially output overly complicated fancy display options :)
if ($Value -ne $Values[-1]){
Write-Host "$X[38;2;255;165;000;22m$Value$X[0m" -nonewline
if ($Value -ne $Values[-2]){Write-Host ", " -nonewline}
}
else {
if ($Values.count -gt 1){
$AndOr = "or"
if ($AndText -eq $True){
$AndOr = "and"
}
if ($NoOr -eq $False){
Write-Host " $AndOr " -nonewline
}
Else {
Write-Host ", " -nonewline
}
}
Write-Host "$X[38;2;255;165;000;22m$Value$X[0m" -nonewline
}
}
}
Function InitialiseCurrentStats {
if ((Test-Path -Path "$Script:WorkingDirectory\Stats.csv") -ne $true){#Create Stats CSV if it doesn't exist
$Null = {} | Select-Object "TotalGameTime","TimesLaunched","LastUpdateCheck","HighRunesFound","UniquesFound","SetItemsFound","RaresFound","MagicItemsFound","NormalItemsFound","Gems","CowKingKilled","PerfectGems" | Export-Csv "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation
Write-Host " Stats.csv created!"
}
do {
Try {
$Script:CurrentStats = import-csv "$Script:WorkingDirectory\Stats.csv" #Get current stats csv details
}
Catch {
Write-Host " Unable to import stats.csv. File corrupt or missing." -foregroundcolor red
}
if ($null -ne $CurrentStats){
#Todo: In the Future add CSV validation checks
$StatsCSVImportSuccess = $True
}
else {#Error out and exit if there's a problem with the csv.
if ($StatsCSVRecoveryAttempt -lt 1){
try {
Write-Host " Attempting Autorecovery of stats.csv from backup..." -foregroundcolor red
Copy-Item -Path $Script:WorkingDirectory\Stats.backup.csv -Destination $Script:WorkingDirectory\Stats.csv -ErrorAction stop
Write-Host " Autorecovery successful!" -foregroundcolor Green
$StatsCSVRecoveryAttempt ++
PressTheAnyKey
}
Catch {
$StatsCSVImportSuccess = $False
}
}
Else {
$StatsCSVRecoveryAttempt = 2
}
if ($StatsCSVImportSuccess -eq $False -or $StatsCSVRecoveryAttempt -eq 2){
Write-Host "`n Stats.csv is corrupted or empty." -foregroundcolor red
Write-Host " Replace with data from stats.backup.csv or delete stats.csv`n" -foregroundcolor red
PressTheAnyKeyToExit
}
}
} until ($StatsCSVImportSuccess -eq $True)
if (-not ($CurrentStats | Get-Member -Name "LastUpdateCheck" -MemberType NoteProperty -ErrorAction SilentlyContinue)){#For update 1.8.1+. If LastUpdateCheck column doesn't exist, add it to the CSV data
$Script:CurrentStats | ForEach-Object {
$_ | Add-Member -NotePropertyName "LastUpdateCheck" -NotePropertyValue "2000.06.28 12:00:00" #previously "28/06/2000 12:00:00 pm"
}
}
ElseIf ($CurrentStats.LastUpdateCheck -eq "" -or $CurrentStats.LastUpdateCheck -like "*/*"){# If script has just been freshly downloaded or has the old Date format.
$Script:CurrentStats.LastUpdateCheck = "2000.06.28 12:00:00" #previously "28/06/2000 12:00:00 pm"
$CurrentStats | Export-Csv "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation
}
}
Function CheckForUpdates {
#Only Check for updates if updates haven't been checked in last 8 hours. Reduces API requests.
if ($Script:CurrentStats.LastUpdateCheck -lt (Get-Date).addHours(-8).ToString('yyyy.MM.dd HH:mm:ss')){# Compare current date and time to LastUpdateCheck date & time.
try {
# Check for Updates
$Releases = Invoke-RestMethod -Uri "https://api.github.com/repos/shupershuff/D2rSPLoader/releases"
$ReleaseInfo = ($Releases | Sort-Object id -desc)[0] #find release with the highest ID.
$Script:LatestVersion = [version[]]$ReleaseInfo.Name.Trim('v')
if ($Script:LatestVersion -gt $Script:CurrentVersion){ #If a newer version exists, prompt user about update details and ask if they want to update.
Write-Host "`n Update available! See Github for latest version and info" -foregroundcolor Yellow -nonewline
if ([version]$CurrentVersion -in (($Releases.name.Trim('v') | ForEach-Object { [version]$_ } | Sort-Object -desc)[2..$releases.count])){
Write-Host ".`n There have been several releases since your version." -foregroundcolor Yellow
Write-Host " Checkout Github releases for fixes/features added. " -foregroundcolor Yellow
Write-Host " $X[38;2;69;155;245;4mhttps://github.com/shupershuff/D2rSPLoader/releases/$X[0m`n"
}
Else {
Write-Host ":`n $X[38;2;69;155;245;4mhttps://github.com/shupershuff/D2rSPLoader/releases/latest$X[0m`n"
}
FormatFunction -Text $ReleaseInfo.body #Output the latest release notes in an easy to read format.
Write-Host; Write-Host
Do {
Write-Host " Your Current Version is v$CurrentVersion."
Write-Host (" Would you like to update to v"+ $Script:LatestVersion + "? $X[38;2;255;165;000;22mY$X[0m/$X[38;2;255;165;000;22mN$X[0m: ") -nonewline
$ShouldUpdate = ReadKey
if ($ShouldUpdate -eq "y" -or $ShouldUpdate -eq "yes" -or $ShouldUpdate -eq "n" -or $ShouldUpdate -eq "no"){
$UpdateResponseValid = $True
}
Else {
Write-Host "`n Invalid response. Choose $X[38;2;255;165;000;22mY$X[0m $X[38;2;231;072;086;22mor$X[0m $X[38;2;255;165;000;22mN$X[0m.`n" -ForegroundColor red
}
} Until ($UpdateResponseValid -eq $True)
if ($ShouldUpdate -eq "y" -or $ShouldUpdate -eq "yes"){#if user wants to update script, download .zip of latest release, extract to temporary folder and replace old D2rSPLoader.ps1 with new D2rSPLoader.ps1
Write-Host "`n Updating... :)" -foregroundcolor green
try {
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") -ErrorAction stop | Out-Null #create temporary folder to download zip to and extract
}
Catch {#if folder already exists for whatever reason.
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") | Out-Null #create temporary folder to download zip to and extract
}
$ZipURL = $ReleaseInfo.zipball_url #get zip download URL
$ZipPath = ($WorkingDirectory + "\UpdateTemp\D2rSPLoader_" + $ReleaseInfo.tag_name + "_temp.zip")
Invoke-WebRequest -Uri $ZipURL -OutFile $ZipPath
if ($Null -ne $releaseinfo.assets.browser_download_url){#Check If I didn't forget to make a version.zip file and if so download it. This is purely so I can get an idea of how many people are using the script or how many people have updated. I have to do it this way as downloading the source zip file doesn't count as a download in github and won't be tracked.
Invoke-WebRequest -Uri $releaseinfo.assets.browser_download_url -OutFile $null | out-null #identify the latest file only.
}
$ExtractPath = ($Script:WorkingDirectory + "\UpdateTemp\")
Expand-Archive -Path $ZipPath -DestinationPath $ExtractPath -Force
$FolderPath = Get-ChildItem -Path $ExtractPath -Directory -Filter "shupershuff*" | Select-Object -ExpandProperty FullName
Copy-Item -Path ($FolderPath + "\D2rSPLoader.ps1") -Destination ($Script:WorkingDirectory + "\" + $Script:ScriptFileName) #using $Script:ScriptFileName allows the user to rename the file if they want
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force #delete update temporary folder
Write-Host " Updated :)" -foregroundcolor green
Start-Sleep -milliseconds 850
& ($Script:WorkingDirectory + "\" + $Script:ScriptFileName)
exit
}
}
$Script:CurrentStats.LastUpdateCheck = (get-date).tostring('yyyy.MM.dd HH:mm:ss')
$Script:LatestVersionCheck = $CurrentStats.LastUpdateCheck
$CurrentStats | Export-Csv -Path "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation #update stats.csv with the new time played.
}
Catch {
Write-Host "`n Couldn't check for updates. GitHub API limit may have been reached..." -foregroundcolor Yellow
Start-Sleep -milliseconds 3500
}
}
#Update (or replace missing) SetTextV2.bas file. This is an newer version of SetText (built by me and ChatGPT) that allows windows to be closed by process ID.
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.bas')) -ne $True){#if SetTextv2.bas doesn't exist, download it.
try {
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") -ErrorAction stop | Out-Null #create temporary folder to download zip to and extract
}
Catch {#if folder already exists for whatever reason.
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") | Out-Null #create temporary folder to download zip to and extract
}
$Releases = Invoke-RestMethod -Uri "https://api.github.com/repos/shupershuff/D2rSPLoader/releases"
$ReleaseInfo = ($Releases | Sort-Object id -desc)[0] #find release with the highest ID.
$ZipURL = $ReleaseInfo.zipball_url #get zip download URL
$ZipPath = ($WorkingDirectory + "\UpdateTemp\D2rSPLoader_" + $ReleaseInfo.tag_name + "_temp.zip")
Invoke-WebRequest -Uri $ZipURL -OutFile $ZipPath
if ($Null -ne $releaseinfo.assets.browser_download_url){#Check If I didn't forget to make a version.zip file and if so download it. This is purely so I can get an idea of how many people are using the script or how many people have updated. I have to do it this way as downloading the source zip file doesn't count as a download in github and won't be tracked.
Invoke-WebRequest -Uri $releaseinfo.assets.browser_download_url -OutFile $null | out-null #identify the latest file only.
}
$ExtractPath = ($Script:WorkingDirectory + "\UpdateTemp\")
Expand-Archive -Path $ZipPath -DestinationPath $ExtractPath -Force
$FolderPath = Get-ChildItem -Path $ExtractPath -Directory -Filter "shupershuff*" | Select-Object -ExpandProperty FullName
Copy-Item -Path ($FolderPath + "\SetText\SetTextv2.bas") -Destination ($Script:WorkingDirectory + "\SetText\SetTextv2.bas")
Write-Host " SetTextV2.bas was missing and was downloaded."
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force #delete update temporary folder
}
}
Function ImportXML { #Import Config XML
try {
$Script:Config = ([xml](Get-Content "$Script:WorkingDirectory\Config.xml" -ErrorAction Stop)).D2SPLoaderConfig
Write-Verbose "Config imported successfully."
}
Catch {
Write-Host "`n Config.xml Was not able to be imported. This could be due to a typo or a special character such as `'&`' being incorrectly used." -foregroundcolor red
Write-Host " The error message below will show which line in the config.xml is invalid:" -foregroundcolor red
Write-Host (" " + $PSitem.exception.message + "`n") -foregroundcolor red
PressTheAnyKeyToExit
}
}
Function ValidationAndSetup {
#
# Note to self, enter in any future additions/removals from config.xml here.
#
#Perform some validation on config.xml. Helps avoid errors for people who may be on older versions of the script and are updating. Will look to remove all of this in a future update.
$Script:Config = ([xml](Get-Content "$Script:WorkingDirectory\Config.xml" -ErrorAction Stop)).D2SPLoaderConfig #import config.xml again for any updates made by the above.
#check if there's any missing config.xml options, if so user has out of date config file.
$AvailableConfigs = #add to this if adding features.
"GamePath",
"CustomLaunchArguments",
"ShortcutCustomIconPath"
$BooleanConfigs =
"ManualSettingSwitcherEnabled",
"DisableVideos",
"AutoBackup",
"CreateDesktopShortcut",
"ForceWindowedMode"
$AvailableConfigs = $AvailableConfigs + $BooleanConfigs
$ConfigXMLlist = ($Config | Get-Member | Where-Object {$_.membertype -eq "Property" -and $_.name -notlike "#comment"}).name
Write-Host
ForEach ($Option in $AvailableConfigs){#Config validation
if ($Option -notin $ConfigXMLlist){
Write-Host " Config.xml file is missing a config option for $Option." -foregroundcolor yellow
Start-Sleep 1
PressTheAnyKey
}
}
if ($Option -notin $ConfigXMLlist){
Write-Host "`n Make sure to grab the latest version of config.xml from GitHub" -foregroundcolor yellow
Write-Host " $X[38;2;69;155;245;4mhttps://github.com/shupershuff/D2rSPLoader/releases/latest$X[0m`n"
PressTheAnyKey
}
if ($Config.GamePath -match "`""){#Remove any quotes from path in case someone ballses this up.
$Script:GamePath = $Config.GamePath.replace("`"","")
}
else {
$Script:GamePath = $Config.GamePath
}
ForEach ($ConfigCheck in $BooleanConfigs){#validate all configs that require "True" or "False" as the setting.
if ($Null -ne $Config.$ConfigCheck -and ($Config.$ConfigCheck -ne $true -and $Config.$ConfigCheck -ne $false)){#if config is invalid
Write-Host " Config option '$ConfigCheck' is invalid." -foregroundcolor Red
Write-Host " Ensure this is set to either True or False.`n" -foregroundcolor Red
PressTheAnyKeyToExit
}
}
if ($Config.ShortcutCustomIconPath -match "`""){#Remove any quotes from path in case someone ballses this up.
$ShortcutCustomIconPath = $Config.ShortcutCustomIconPath.replace("`"","")
}
else {
$ShortcutCustomIconPath = $Config.ShortcutCustomIconPath
}
#Check Windows Game Path for D2r.exe is accurate.
if ((Test-Path -Path "$GamePath\d2r.exe") -ne $True){
Write-Host " Gamepath is incorrect. Looks like you have a custom D2r install location!" -foregroundcolor red
Write-Host " Edit the GamePath variable in the config file.`n" -foregroundcolor red
PressTheAnyKeyToExit
}
#Check Grail app path actually exists and if not throw an error
if ("" -ne $Config.GrailAppExecutablePath){
if ((Test-Path -Path $Config.GrailAppExecutablePath) -ne $true){
Write-Host " Grail app '$(split-path $Config.GrailAppExecutablePath -leaf)' not found." -foregroundcolor red
formatfunction -IsError -Text "Couldn't find the Grail application in '$(split-path $Config.GrailAppExecutablePath)'"
Write-Host " Double check the grail application path and update config.xml to fix." -foregroundcolor red
PressTheAnyKeyToExit
}
}
#Check Run Timer app path actually exists and if not throw an error
if ("" -ne $Config.RunTimerAppExecutablePath){
if ((Test-Path -Path $Config.RunTimerAppExecutablePath) -ne $true){
Write-Host " Run Timer app '$(split-path $Config.RunTimerAppExecutablePath -leaf)' not found." -foregroundcolor red
formatfunction -IsError -Text "Couldn't find the Run Timer application in '$(split-path $Config.RunTimerAppExecutablePath)'"
Write-Host " Double check the Run Timer application path and update config.xml to fix." -foregroundcolor red
PressTheAnyKeyToExit
}
}
# Create Shortcut
if ($Config.CreateDesktopShortcut -eq $True){
$DesktopPath = [Environment]::GetFolderPath("Desktop")
$Targetfile = "-ExecutionPolicy Bypass -File `"$WorkingDirectory\$ScriptFileName`""
$ShortcutFile = "$DesktopPath\D2R Single Player.lnk"
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = $TargetFile
if ($ShortcutCustomIconPath.length -eq 0){
$Shortcut.IconLocation = "$Script:GamePath\D2R.exe"
}
Else {
$Shortcut.IconLocation = $ShortcutCustomIconPath
}
$Shortcut.Save()
}
#Check if SetTextv2.exe exists, if not, compile from SetTextv2.bas. SetTextv2.exe is what's used to rename the windows.
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.exe')) -ne $True){ #-PathType Leaf check windows renamer is configured.
Write-Host "`n First Time run!`n" -foregroundcolor Yellow
Write-Host " SetTextv2.exe not in .\SetText\ folder and needs to be built."
if ((Test-Path -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe") -ne $True){#check that .net4.0 is actually installed or compile will fail.
Write-Host " .Net v4.0 not installed. This is required to compile the Window Renamer for Diablo." -foregroundcolor red
Write-Host " Download and install it from Microsoft here:" -foregroundcolor red
Write-Host " https://dotnet.microsoft.com/en-us/download/dotnet-framework/net40" #actual download link https://dotnet.microsoft.com/en-us/download/dotnet-framework/thank-you/net40-web-installer
PressTheAnyKeyToExit
}
Write-Host " Compiling SetTextv2.exe from SetTextv2.bas..."
& "C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" -target:winexe -out:"`"$WorkingDirectory\SetText\SetTextv2.exe`"" "`"$WorkingDirectory\SetText\SetTextv2.bas`"" | out-null #/verbose #actually compile the bastard
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.exe')) -ne $True){#if it fails for some reason and settextv2.exe still doesn't exist.
Write-Host " SetTextv2 Could not be built for some reason :/"
PressTheAnyKeyToExit
}
Write-Host " Successfully built SetTextv2.exe for Diablo 2 Launcher script :)" -foregroundcolor green
Start-Sleep -milliseconds 4000 #a small delay so the first time run outputs can briefly be seen
}
#Check Handle64.exe downloaded and placed into correct folder
$Script:WorkingDirectory = ((Get-ChildItem -Path $PSScriptRoot)[0].fullname).substring(0,((Get-ChildItem -Path $PSScriptRoot)[0].fullname).lastindexof('\'))
if ((Test-Path -Path ($workingdirectory + '\Handle\Handle64.exe')) -ne $True){ #-PathType Leaf check windows renamer is configured.
try {
Write-Host "`n Handle64.exe not in .\Handle\ folder. Downloading now..." -foregroundcolor Yellow
try {
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\Handle\ExtractTemp\") -ErrorAction stop | Out-Null #create temporary folder to download zip to and extract
}
Catch {#if folder already exists for whatever reason.
Remove-Item -Path ($Script:WorkingDirectory + "\Handle\ExtractTemp\") -Recurse -Force
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\Handle\ExtractTemp\") | Out-Null #create temporary folder to download zip to and extract
}
$ZipURL = "https://download.sysinternals.com/files/Handle.zip" #get zip download URL
$ZipPath = ($WorkingDirectory + "\Handle\ExtractTemp\")
Invoke-WebRequest -Uri $ZipURL -OutFile ($ZipPath + "\Handle.zip")
Expand-Archive -Path ($ZipPath + "\Handle.zip") -DestinationPath $ZipPath -Force
Copy-Item -Path ($ZipPath + "Handle64.exe") -Destination ($Script:WorkingDirectory + "\Handle\")
Remove-Item -Path ($Script:WorkingDirectory + "\Handle\ExtractTemp\") -Recurse -Force #delete update temporary folder
Write-Host " Successfully downloaded Handle64.exe :)" -ForeGroundcolor Green
Start-Sleep -milliseconds 2024
}
Catch {
Write-Host " Handle.zip couldn't be downloaded." -foregroundcolor red
FormatFunction -text "It's possible the download link changed. Try checking the Microsoft page or SysInternals.com site for a download link and ensure that handle64.exe is placed in the .\Handle\ folder." -IsError
Write-Host "`n $X[38;2;69;155;245;4mhttps://learn.microsoft.com/sysinternals/downloads/handle$X[0m"
Write-Host " $X[38;2;69;155;245;4mhttps://download.sysinternals.com/files/Handle.zip$X[0m`n"
PressTheAnyKeyToExit
}
}
}
Function DisableVideos {
#Diable Videos feature
$VideoFiles = @(
"blizzardlogos.webm",
"d2intro.webm",
"logoanim.webm",
"d2x_intro.webm",
"act2\act02start.webm",
"act3\act03start.webm",
"act4\act04start.webm",
"act4\act04end.webm",
"act5\d2x_out.webm"
)
if ($Config.DisableVideos -eq $True){
if ($Config.CustomLaunchArguments -match "-mod"){
$pattern = "-mod\s+(\S+)" #pattern to find the first word after -mod
if ($Config.CustomLaunchArguments -match $pattern){
$ModName = $matches[1]
$ModPath = $Config.GamePath + "\mods\$ModName\$ModName.mpq\data\hd\global\video"
if (-not (Test-Path "$ModPath\blizzardlogos.webm")){
Write-Host " You've opted to disable game videos however a mod is already being used." -ForegroundColor Yellow
Do {
Write-Host " Attempt to update the current mod ($ModName) to disable videos? $X[38;2;255;165;000;22mY$X[0m/$X[38;2;255;165;000;22mN$X[0m: " -nonewline
$ShouldUpdate = ReadKey
if ($ShouldUpdate -eq "y" -or $ShouldUpdate -eq "n"){
$UpdateResponseValid = $True
write-host
}
Else {
Write-Host "`n Invalid response. Choose $X[38;2;255;165;000;22mY$X[0m $X[38;2;231;072;086;22mor$X[0m $X[38;2;255;165;000;22mN$X[0m.`n" -ForegroundColor red
}
} Until ($UpdateResponseValid -eq $True)
if ($ShouldUpdate -eq "y"){
if (-not (Test-Path "$ModPath\act2")){
Write-Debug " Creating folders required for disabling D2r videos..."
New-Item -ItemType Directory -Path $ModPath -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act2" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act3" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act4" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act5" -ErrorAction SilentlyContinue | Out-Null
Write-Debug " Created folder: $ModPath"
start-sleep -milliseconds 123
}
foreach ($File in $VideoFiles){
New-Item -ItemType File -Path "$ModPath\$File" -ErrorAction SilentlyContinue | Out-Null
}
Write-Debug " Created dummy D2r videos."
start-sleep -milliseconds 222
}
else {
Write-Host " D2r videos have not been disabled.`n" -foregroundcolor red
start-sleep -milliseconds 256
}
}
else {# If blizzardlogos.webm does exist, lets confirm that all videos are indeed 0 bytes and if not, make it so.
foreach ($File in $VideoFiles){
try {
if ((Get-Item "$ModPath\$File" -ErrorAction Stop).Length -gt 0){
$FileName = $File -replace "^[^\\]+\\", "" #remove "act2\" from string if needed.
Rename-Item -Path "$ModPath\$File" -NewName "$FileName.backup" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType File -Path "$ModPath\$File" -ErrorAction SilentlyContinue | Out-Null
}
}
Catch {
Write-Debug " Creating folders required for disabling D2r videos..."
New-Item -ItemType Directory -Path $ModPath -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act2" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act3" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act4" -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act5" -ErrorAction SilentlyContinue | Out-Null
Write-Debug " Created folder: $ModPath"
New-Item -ItemType File -Path "$ModPath\$File" -ErrorAction SilentlyContinue | Out-Null
write-host "derp $file"
}
}
}
}
}
elseif ($Config.CustomLaunchArguments -match "-direct -txt"){ #if user has extracted files.
foreach ($File in $VideoFiles){
if (Test-Path "$($Config.GamePath)\Data\hd\global\video\$File"){
if ((Get-Item "$($Config.GamePath)\Data\hd\global\video\$File").Length -gt 0){ #check if file is larger than 0 bytes and if so backup original file and replace with 0 byte file.
$FileName = $File -replace "^[^\\]+\\", "" #remove "act2\" from string if needed.
try { #try renaming file. If it can't be renamed, it must already exist, therefore delete the video file.
Rename-Item -Path "$($Config.GamePath)\Data\hd\global\video\$File" -NewName "$FileName.backup" -ErrorAction Stop | Out-Null
}
Catch {
Remove-Item -Path "$($Config.GamePath)\Data\hd\global\video\$File" -ErrorAction SilentlyContinue | Out-Null
}
}
}
New-Item -ItemType File -Path "$($Config.GamePath)\Data\hd\global\video\$File" | Out-Null
}
}
else { #if user has not extracted files, launch with mod
$ModPath = $Config.GamePath + "\mods\DisableVideos\DisableVideos.mpq\data\hd\global\video"
if (-not (Test-Path "$ModPath")){
Write-Host " Creating needed folders for disabling D2r videos..."
New-Item -ItemType Directory -Path $ModPath -ErrorAction stop | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act2" -ErrorAction stop | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act3" -ErrorAction stop | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act4" -ErrorAction stop | Out-Null
New-Item -ItemType Directory -Path "$ModPath\act5" -ErrorAction stop | Out-Null
start-sleep -milliseconds 213
foreach ($File in $VideoFiles){
$FileName = $File -replace "^[^\\]+\\", "" #remove "act2\" from string if needed.
New-Item -ItemType File -Path "$ModPath\$File" | Out-Null
}
$data = @{
name = "DisableVideos"
savepath = "../"
}
$json = $data | ConvertTo-Json -Depth 1 -Compress # Convert the hashtable to JSON
Set-Content -Path ($Config.GamePath + "\mods\DisableVideos\DisableVideos.mpq\modinfo.json") -Value $json -Encoding UTF8 # Write the JSON content to the file
Write-Host " Created dummy D2r videos.`n" -ForegroundColor Green
start-sleep -milliseconds 222
}
$Script:StartWithDisableVideosMod = $True
}
}
else {
Write-Debug "Videos are enabled"
$Script:StartWithDisableVideosMod = $False
if ($Config.CustomLaunchArguments -match "-direct -txt"){ #if user has extracted files.
foreach ($File in $VideoFiles){
if (Test-Path "$($Config.GamePath)\Data\hd\global\video\$File"){
if ((Get-Item "$($Config.GamePath)\Data\hd\global\video\$File" -ErrorAction Stop).Length -eq 0){ #check if file is l0 bytes and if so remove 0 byte file and restore original file.
$FileName = $File -replace "^[^\\]+\\", "" #remove "act2\" from string if needed.
Remove-Item -Path "$($Config.GamePath)\Data\hd\global\video\$File"
write-debug "removed $($Config.GamePath)\Data\hd\global\video\$File"
Rename-Item -Path "$($Config.GamePath)\Data\hd\global\video\$File.backup" -NewName "$FileName" -erroraction SilentlyContinue | Out-Null #attempt to retrieve original file if it's there.
write-debug "renamed $($Config.GamePath)\Data\hd\global\video\$File.backup"
}
}
}
}
elseif ($Config.CustomLaunchArguments -match "mod"){ #if user is using a mod.
$pattern = "-mod\s+(\S+)" #pattern to find the first word after -mod
if ($Config.CustomLaunchArguments -match $pattern){
$ModName = $matches[1]
$ModPath = $Config.GamePath + "\mods\$ModName\$ModName.mpq\data\hd\global\video"
if (-not(Test-Path "$ModPath\act2\act02start.webm.backup")){#figure out if we should try rename files from backup or just delete.
$Replace = $True
}
foreach ($File in $VideoFiles){
if (Test-Path "$ModPath\$File"){
if ((Get-Item "$ModPath\$File").Length -eq 0){ #check if file is 0 bytes and if so remove 0 byte file and restore original file.
$FileName = $File -replace "^[^\\]+\\", "" #remove "act2\" from string if needed.
if ($Replace = $True){
try {
Rename-Item -Path "$ModPath\$File.backup" -NewName "$FileName" -erroraction stop | Out-Null #Attempt to see if there's a backup we can restore from in the mod folder. Unlikely.
}
Catch {
Remove-Item -Path "$ModPath\$File"
}
}
Else {
Remove-Item -Path "$ModPath\$File"
if ((Get-Item "$($Config.GamePath)\Data\hd\global\video\$File").Length -eq 0){#check to see if we can rely on original game files. If this is true, original files are empty and can't be used
try {
Rename-Item -Path "$ModPath\$File.backup" -NewName "$FileName" -erroraction stop | Out-Null #Attempt to see if there's a backup we can restore from in the mod folder. Unlikely.
}
Catch {
formatfunction -IsError -indent 2 "Couldn't restore $($Config.GamePath)\Data\hd\global\video\$File.`nYou may need to repair your game from the Battlenet client."
}
}
}
}
}
}
}
}
}
}
Function ImportCSV { #Import Character CSV
do {
try {
$Script:CharactersCSV = import-csv "$Script:WorkingDirectory\characters.csv" #import all characters from csv
}
Catch {
FormatFunction -text "`ncharacters.csv does not exist. Make sure you create this file. Redownload from Github if needed." -IsError
PressTheAnyKeyToExit
}
if ($Null -ne $Script:CharactersCSV){
if ($Null -ne ($CharactersCSV | Where-Object {$_.CharacterName -eq ""})){
$Script:CharactersCSV = $Script:CharactersCSV | Where-Object {$_.CharacterName -ne ""} # To account for user error, remove any empty lines from characters.csv
}
$CharacterCSVImportSuccess = $True
}
else {
if (Test-Path ($Script:WorkingDirectory + "\characters.backup.csv")){ #Figure out if script is being run for first time by checking if characters.backup.csv doesn't exist, if so, don't try perform recovery.
if ($CharacterCSVRecoveryAttempt -lt 1){#Error out and exit if there's a problem with the csv.
try {
Write-Host " Issue with characters.csv. Attempting Autorecovery from backup..." -foregroundcolor red
Copy-Item -Path $Script:WorkingDirectory\characters.backup.csv -Destination $Script:WorkingDirectory\characters.csv -erroraction stop
Write-Host " Autorecovery successful!" -foregroundcolor Green
$CharacterCSVRecoveryAttempt ++
PressTheAnyKey
}
Catch {
$CharacterCSVImportSuccess = $False
}
}
Else {
$CharacterCSVRecoveryAttempt = 2
}
if ($CharacterCSVImportSuccess -eq $False -or $CharacterCSVRecoveryAttempt -eq 2){
Write-Host "`n There's an issue with characters.csv." -foregroundcolor red
Write-Host " Please ensure that this is filled out correctly and rerun the script." -foregroundcolor red
Write-Host " Alternatively, rebuild CSV from scratch or restore from characters.backup.csv`n" -foregroundcolor red
PressTheAnyKeyToExit
}
}
else {
$CharacterCSVImportSuccess = $True
}
}
} until ($CharacterCSVImportSuccess -eq $True)
$Script:CurrentStats = import-csv "$Script:WorkingDirectory\Stats.csv"
([int]$Script:CurrentStats.TimesLaunched) ++
if ($CurrentStats.TotalGameTime -eq ""){
$Script:CurrentStats.TotalGameTime = 0 #prevents errors from happening on first time run.
}
try {
$CurrentStats | Export-Csv -Path "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation #update Stats.csv with Total Time played.
}
Catch {
Write-Host " Couldn't update stats.csv" -foregroundcolor yellow
}
#Make Backup of CSV.
# Added this in as I had BSOD on my PC and noticed that this caused the files to get corrupted.
Copy-Item -Path ($Script:WorkingDirectory + "\stats.csv") -Destination ($Script:WorkingDirectory + "\stats.backup.csv")
if ($Null -ne $Script:CharactersCSV){#Don't create backup csv if characters file isn't populated yet. prevents issues with first time run or running on a computer that doesnt have D2r char saves yet.
Copy-Item -Path ($Script:WorkingDirectory + "\characters.csv") -Destination ($Script:WorkingDirectory + "\characters.backup.csv")
}
}
Function CloudBackupSetup {
<#
Author: Shupershuff
Version: 1.0
Usage:
Close D2r if open. Run script to move Diablo 2 save folder from "C:\Users\<USERNAME>\Saved Games\Diablo II Resurrected" to your chosen cloud storage.
Purpose:
Quick and easy way for folk to ensure game saves are saved to the cloud instead of local only.
Instructions: See GitHub readme https://github.com/shupershuff/D2rSinglePlayerBackup
Notes:
- Google Drive only works if it's configured to store files locally AND on the cloud. In other words, the "Mirror files" option is chosen instead of "Stream files"/
- If ya want to do this yourself (for anything) without a script, just copy the data to a cloud sync'd path and use this command in CMD: mklink /J <DefaultSaveGamePath> <CloudSaveGamePath>
#>
##################
# Config Options #
##################
$SaveFolderName = "Saved Games" #Name of the folder which will be created.
##########
# Script #
##########
write-host
formatfunction -indents 1 "This will ensure your game files are saved in a cloud sync'd location."
write-host
$DefaultSaveGamePath = $Script:WindowsSavedGameLocation
$OneDriveSavePath = ("C:\Users\" + $env:username + "\OneDrive\")
$DropboxSavePath = ("C:\Users\" + $env:username + "\Dropbox\")
$GoogleDriveSavePath = ("C:\Users\" + $env:username + "\My Drive\")
###Check if junction has already been created ###
$SavedGamesFolder = $Script:WindowsSavedGameLocation.replace("\Diablo II Resurrected","")
# Run cmd's dir command to get junction info, ensuring the path is quoted
$junctionInfo = cmd /c "dir `"$SavedGamesFolder`" /AL"
# Define a regex pattern to match the "Diablo II Resurrected" junction and its target path
$regexPattern = "\s+<JUNCTION>\s+Diablo II Resurrected\s+\[([^\]]+)\]"
# Check if the output contains the specific junction target path for "Diablo II Resurrected"
if ("$junctionInfo" -match $regexPattern){ #Warn user if they've already ran this script and moved the game folder.
# Extract the target path using the match
$JunctionTarget = $matches[1]
$RecreateJunction = $True
formatfunction -indents 1 -IsWarning -text "Warning, the D2r Savegame folder is already redirected."
formatfunction -indents 1 -IsWarning -text "This is currently pointing to: '$JunctionTarget'"
Write-host
Write-host " If you're happy with game files already being saved to this cloud folder," -foregroundcolor yellow
Write-host " choose cancel ($X[38;2;255;165;000;22mc$X[0m" -nonewline -foregroundcolor yellow; write-host ")" -foregroundcolor yellow
formatfunction -indents 1 -IsWarning -text "Otherwise, continue with the script to point it to the new cloud location."
Write-Host "`n Press '$X[38;2;255;165;000;22mc$X[0m' to cancel or any other key to proceed: " -nonewline
if (readkey -eq "c"){
return $False
}
Write-host
}
else {
Write-Verbose "No junction for 'Diablo II Resurrected' found in $SavedGamesFolder."
}
do {
$LastOption = 3
$OptionText = " or 3"
write-host "`n Options are:"
write-host " 1 - OneDrive"
write-host " 2 - Dropbox"
write-host " 3 - Google Drive"
if ($RecreateJunction -eq $True) {
write-host " 4 - Move folder back to default (local) location"
$LastOption ++
$OptionText = ", 3 or 4"
}
write-host
$CloudOption = [int](ReadKey " Enter the option would you like to choose (1, 2$OptionText): ").tostring()
if ($CloudOption -notin 1..$LastOption){
write-host " Please choose option 1, 2$OptionText.`n" -foregroundcolor red
}
} until ($CloudOption -in 1..$LastOption)
if ($CloudOption -eq 1){
write-host " Configuring for OneDrive...`n"
$CloudSaveGamePath = ($OneDriveSavePath + $SaveFolderName + "\Diablo II Resurrected")
}
if ($CloudOption -eq 2){
write-host " Configuring for Dropbox...`n"
$CloudSaveGamePath = ($DropboxSavePath + $SaveFolderName + "\Diablo II Resurrected")
}
if ($CloudOption -eq 3){
write-host " Configuring for Google Drive...`n"
$CloudSaveGamePath = ($GoogleDriveSavePath + $SaveFolderName + "\Diablo II Resurrected")
formatfunction -indents 1 -IsWarning "Note, for this to save to the cloud, you need to configure Google Drive to store files locally AND on the cloud"
formatfunction -indents 1 -IsWarning "To do this, go into Google Drive preferences and change My Drive syncing options from 'Stream files' to 'Mirror files'.`n"
PressTheAnyKey
}
if ($RecreateJunction -eq $True){
write-verbose "Removing Existing Junction"
Remove-Item -Path $DefaultSaveGamePath -recurse -Force
New-Item $DefaultSaveGamePath -type directory | out-null
write-verbose "Moving Savegame data from previous junction target back to default location"
Get-ChildItem -Path $JunctionTarget | Copy-Item -Destination $DefaultSaveGamePath -Force -recurse
if ($CloudOption -eq 4){
Write-Host " Moved Saved Game data back to default location.`n " -nonewline -foregroundcolor green
$DefaultSaveGamePath
Write-Host
Return $True