-
Notifications
You must be signed in to change notification settings - Fork 6
/
chrupd.cmd
2204 lines (2106 loc) · 81 KB
/
chrupd.cmd
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
<# :
@echo off & SETLOCAL & SET "_PS=powershell.exe -NoLogo -NoProfile" & SET "_ARGS=\"%~dp0" %*"
%_PS% "&(Invoke-Command {[ScriptBlock]::Create('$Args=@(&{$Args} %_ARGS%);'+((Get-Content \"%~f0\") -Join [char]10))})"
ENDLOCAL & dir "%~f0.tmp" >nul 2>&1 && move /Y "%~f0" "%~f0.bak" >nul 2>&1 && move /Y "%~f0.tmp" "%~f0" >nul 2>&1 & GOTO :EOF
#>
<#
.SYNOPSIS
-------------------------------------------------------------------------
20240630 MK: Simple Chromium Updater (chrupd.cmd)
-------------------------------------------------------------------------
.DESCRIPTION
Installs latest available Chromium version
Checks RSS feed from "chromium.woolyss.com" and GitHub API
Downloads, verifies sha/md5 hash and runs installer:
default name: "Hibbiki", channel "stable", arch "64bit"
set options using cli args or under CONFIGURATION in script
.EXAMPLE
PS> .\chrupd.ps1 -name Marmaduke -arch 64bit -channel stable [-crTask]
#>
<# ------------------------------------------------------------------------- #>
<# CONFIGURATION: #>
<# ------------------------------------------------------------------------- #>
<# Make sure the combination of name and channel is correct. #>
<# See "chrupd.cmd -h" or README.md for more options and details. #>
<# ------------------------------------------------------------------------- #>
$cfg = @{
name = "Hibbiki"; <# Name of Chromium release (fka "editor") #>
channel = "stable"; <# dev, stable #>
arch = "64bit"; <# Architecture: 32bit or 64bit (default) #>
log = $true <# enable or disable logging <$true|$false> #>
cAutoUp = $true <# auto update this script <$true|$false> #>
};
<# END OF CONFIGURATION ---------------------------------------------------- #>
<####################>
<# SCRIPT VARIABLES #>
<####################>
<# Set-StrictMode -Version 3.0 #>
<# the vars defined below can be changed if you want, be careful as they can break the script #>
<# VAR: define registry keys and paths with chromium version #>
[hashtable]$versionRegKeys = @{
User = [ordered]@{
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Chromium" = "Version"
"HKCU:\SOFTWARE\Chromium" = "pv"
};
System = [ordered]@{
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Chromium" = "Version"
"HKLM:\SOFTWARE\Chromium" = "pv"
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Chromium" = "Version"
"HKLM:\SOFTWARE\WOW6432Node\Chromium" = "pv"
}
}
[hashtable]$versionPaths = @{
User = @( "${env:LocalAppData}\Chromium\Application" );
System = @( "${env:ProgramFiles}\Chromium\Application", "${env:ProgramFiles(x86)}\Chromium\Application" ) <# 64bit, 32bit #>
}
<# VAR: define releases #>
<# items[$name] = @{ author, source, url, repository, filemask [alias, no_hash, no_arch, disabled] } #>
[hashtable]$items = @{
"Official" = @{
enabled = $true;
author = "The Chromium Authors";
fmt = "XML";
url = "https://www.chromium.org";
repo = "https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/";
filemask = "mini_installer.exe";
alias = "Chromium";
};
"Hibbiki" = @{
enabled = $true;
author = "Hibbiki";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/Hibbiki/chromium-win64/releases/download/";
filemask = "mini_installer.sync.exe";
};
"Marmaduke" = @{
author = "Marmaduke";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/macchrome/winchrome/releases/download/";
filemask = "mini_installer.exe";
};
"Ungoogled-Marmaduke" = @{
author = "Marmaduke";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/macchrome/winchrome/releases/download/";
filemask = "ungoogled_mini_installer.exe";
alias = @( "Ungoogled-Marmaduke", "Ungoogled" );
};
"Ungoogled-Eloston" = @{
author = "Eloston";
fmt = "JSON";
url = "https://github.com/ungoogled-software/ungoogled-chromium-windows";
repo = "https://api.github.com/repos/ungoogled-software/ungoogled-chromium-windows/releases";
filemask = "ungoogled-chromium_";
no_hash = $true;
alias = @( "Eloston-Ungoogled", "Eloston" );
};
"justclueless" = @{
author = "justclueless";
fmt = "JSON";
url = "https://github.com/justclueless/chromium-win64";
repo = "https://api.github.com/repos/justclueless/chromium-win64/releases";
filemask = "mini_installer.exe";
};
"RobRich" = @{
author = "RobRich999";
fmt = "JSON";
url = "https://github.com/RobRich999/Chromium_Clang";
repo = "https://api.github.com/repos/RobRich999/Chromium_Clang/releases";
filemask = "mini_installer.exe";
alias = "RobRich999";
};
"Supermium" = @{
author = "win32ss";
fmt = "JSON";
url = "https://github.com/win32ss/supermium";
repo = "https://api.github.com/repos/win32ss/supermium/releases";
filemask = "supermium_";
no_hash = $true;
};
"thorium" = @{
author = "Alex313031";
fmt = "JSON";
url = "https://github.com/Alex313031/Thorium-Win";
repo = "https://api.github.com/repos/Alex313031/Thorium-Win/releases";
filemask = "thorium_.*mini_installer";
no_hash = $true;
no_arch = $true;
alias = @( "Thorium", "Thorium-Win" );
};
"thorium-avx2" = @{
author = "Alex313031";
fmt = "JSON";
url = "https://github.com/Alex313031/Thorium-Win-AVX2";
repo = "https://api.github.com/repos/Alex313031/Thorium-Win-AVX2/releases";
filemask = "thorium_.*mini_installer";
no_hash = $true;
no_arch = $true;
alias = @( "Thorium-Win-AVX2" );
};
"thorium-legacy" = @{
author = "Alex313031";
fmt = "JSON";
url = "https://github.com/Alex313031/thorium-legacy";
repo = "https://api.github.com/repos/Alex313031/thorium-legacy/releases";
filemask = "thorium_.*mini_installer|Thorium_.*\d\d\d";
no_hash = $true;
};
<# DISABLED: not updated anymore (2019) #>
"ThumbApps" = @{
author = "ThumbApps";
fmt = "XML";
url = "http://www.thumbapps.org";
repo = "https://netix.dl.sourceforge.net/project/thumbapps/Internet/Chromium/";
filemask = "ChromiumPortable_.*_Dev_32_64_bit.paf"
no_hash = $true;
disabled = $true;
}; #>
<# DISABLED: portapps seems no longer updated (dec 24, 2024) #>
"Ungoogled-Portable" = @{
author = "Portapps";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/portapps/ungoogled-chromium-portable/releases/";
filemask = "ungoogled-chromium-";
alias = "Ungoogled-Portapps";
disabled = $true;
};
<# REMOVED: not added to woolyss' rss feed
"justclueless" = @{
author = "justclueless";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/justclueless/chromium/releases/";
filemask = "mini_installer.exe"
disabled = $true;
}; #>
<# REMOVED: discontinued (Mar 29 2022)
"RobRich" = @{
author = "RobRich";
fmt = "XML";
url = "https://chromium.woolyss.com";
repo = "https://github.com/RobRich999/Chromium_Clang/releases/download/";
filemask = "mini_installer.exe"
disabled = $true;
}; #>
<# REMOVED: chromium-ungoogled from github (before woolyss added it)
"Ungoogled-Marmaduke" = @
author = "Marmaduke";
fmt = "JSON";
url = "https://github.com/macchrome/winchrome";
repo = "https://api.github.com/repos/macchrome/winchrome/releases";
filemask = "ungoogled_mini_installer.exe";
disabled = $true;
}; #>
}
<# VAR: define os #>
<# Windows @(majorVer, minorVer, build, osType[1=ws,3=server], tsMode) #>
[hashtable]$osObj = @{
winVer = [ordered]@{
"Windows 11" = @(10, 0, 22000, 1, 1);
"Windows 10" = @(10, 0, 00000, 1, 1);
"Windows 8.1" = @( 6, 3, 00000, 1, 1);
"Windows 8" = @( 6, 2, 00000, 1, 1);
"Windows 7" = @( 6, 1, 00000, 1, 2);
"Windows Vista" = @( 6, 0, 00000, 1, 2);
"Windows XP 64bit" = @( 5, 2, 00000, 1, 3);
"Windows XP" = @( 5, 1, 00000, 1, 3);
"Windows Server 2022" = @(10, 0, 20285, 3, 1);
"Windows Server 2019" = @(10, 0, 17134, 3, 1);
"Windows Server 2016" = @(10, 0, 00000, 3, 1);
"Windows Server 2012 R2" = @( 6, 3, 00000, 3, 1);
"Windows Server 2012" = @( 6, 2, 00000, 3, 1);
"Windows Server 2008 R2" = @( 6, 1, 00000, 3, 2);
"Windows Server 2008" = @( 6, 0, 00000, 3, 2);
"Windows Server 2003" = @( 5, 2, 00000, 3, 3);
}
osTypeName = @{
1 = "Workstation";
2 = "DC";
3 = "Server";
}
taskModeName = @{
0 = "Auto";
1 = "Normal";
2 = "Legacy";
3 = "Schtasks Command"
}
}
<# VAR: define 7z locations #>
[hashtable]$7zConfig = @{
"Paths" = (
"7z.exe",
"7za.exe",
"$env:ProgramFiles\7-Zip\7z.exe",
"$env:ProgramData\chocolatey\tools\7z.exe",
"$env:ProgramData\chocolatey\bin\7z.exe"
);
"Urls" = @{
"7zip.org" = @{ hash = "C136B1467D669A725478A6110EBAAAB3CB88A3D389DFA688E06173C066B76FCF"; url = "https://www.7-zip.org/a/7za920.zip" };
"github-chromium" = @{ hash = "EA308C76A2F927B160A143D94072B0DCE232E04B751F0C6432A94E05164E716D"; url = "https://github.com/chromium/chromium/raw/master/third_party/lzma_sdk/Executable/7za.exe" };
"googlesource.com" = @{ hash = "EA308C76A2F927B160A143D94072B0DCE232E04B751F0C6432A94E05164E716D"; url = "https://chromium.googlesource.com/chromium/src.git/+/0a6a88b4a4c747c3d95c41fb3f9fc5cc726d04ba/third_party/lzma_sdk/Executable/7za.exe?format=TEXT" };
"chocolatey.org" = @{ hash = "31FD52F8996986623CF52C3B4D0F7AC74A9DEC63FC16C902CEF673EED550C435"; url = "https://chocolatey.org/7za.exe" };
}
}
<# VAR: define paths to extact and install archives #>
[object]$archiveInstallPaths = @(
"$env:LocalAppData\Chromium\Application",
"$([Environment]::GetFolderPath('Desktop'))",
"$env:USERPROFILE\Desktop",
"$env:TEMP"
)
<# VAR: define task user msgs #>
[hashtable]$taskMsg = @{
descr = "Download and install latest Chromium version";
create = "Creating Daily Task `"{0}`" in Task Scheduler...";
failed = "Creating Scheduled Task failed.";
problem = "Something went wrong...";
exists = "Scheduled Task already exists.";
notfound = "Scheduled Task not found.";
remove = "Removing Daily Task `"{0}`" from Task Scheduler...";
rmfailed = "Could not remove Task:";
notask = "Scheduled Task already removed.";
manual = "Run `"{0} -manTask`" for manual instructions";
export = "Run `"{0} -xmlTask`" to export a Task XML File"
}
[string]$noMatchMsg = @"
Unable to find new version. If settings are correct, it's possible
the script needs to be updated or there could be an issue with
the RSS feed from `"chromium.woolyss.com`" or the GitHub REST API.`r`n
"@
[hashtable]$archRe = @{
'64-bit' = '(x64|win64|x64|[._-]64[._-])';
'32-bit' = '(x86|win32|x32|[._-]32[._-])'
}
[hashtable]$hashLen = @{
'SHA1' = 40;
'SHA256' = 64;
'SHA512' = 128;
}
<# check if we're dot sourced #>
[boolean]$dotSourced = $false
if ($MyInvocation.InvocationName -eq '.' -or $MyInvocation.Line -eq '') {
$dotSourced = $true
}
<# copy args so we keep original array unchanged #>
[object]$_Args = $Args
[string]$scriptDir = $_Args[0]
<# XXX: Order matters for 'script functions'; keep them on top, before the rest of script #>
<# SCRIPT FUNC: test var #>
function script:Test-Variable($v) {
try {
$varExists = (Test-Path variable:$v)
$varIsEmpty = [string]::IsNullOrWhiteSpace($(Get-Variable "$v" -Scope 1 -ValueOnly -EA 0 -WA 0))
} catch {
$false
}
if ($varExists -and (-not $varIsEmpty)) {
return $true
}
return $false
}
<# VAR: set script dir, cmd and log #>
<# XXX: EA|WA = ErrorAction|WarningAction: 0=SilentlyContinue 1=Stop 2=Continue 3=Inquire 4=Ignore 5=Suspend #>
if ( (Test-Variable "scriptDir") -and (&Test-Path -EA 4 -WA 4 $scriptDir)) {
$rm = $_Args[0]
$_Args = $_Args | Where-Object { $_ -ne $rm }
} else {
$scriptDir = ($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.\'))
}
[string]$logFile = $scriptDir + "\chrupd.log"
[string]$scriptName = "Simple Chromium Updater"
[string]$scriptCmd = "chrupd.cmd"
[string]$installLog = "$env:TEMP\chromium_installer.log"
if ($PSCommandPath) {
$scriptDir = Split-Path -parent $PSCommandPath
$scriptCmd = (Get-Item $PSCommandPath).Name
} elseif ($MyInvocation.MyCommand.Name) {
$scriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
$scriptCmd = $MyInvocation.MyCommand.Name
}
<# VAR: define default values #>
[int]$scheduler = 0
[int]$list = 0
<# debug #>
[int]$debug = 0
[int]$fakeVer = 0
[int]$force = 0
[int]$ignVer = 0
[int]$script:ignHash = 0
<# tasks #>
[int]$tsMode = [int]$crTask = [int]$rmTask = [int]$shTask = [int]$xmlTask = [int]$manTask = [int]$noVbs = [int]$confirm = 0
<# advanced options #>
[string]$proxy = ""
[string]$linkArgs = ""
[string]$vtApikey = ""
[int]$appDir = 0
[int]$sysLvl = 0
[int]$cAutoUp = 1
[bool]$logFileOk = $false
[string]$chrInstall = "User"
[int]$ignDotSrc = 0
if ($dotSourced) {
[int]$cAutoUp = 0
}
[string]$tag = ""
<# SET: chrupd script version #>
[string]$curScriptDate = (Select-String -EA 0 -WA 0 -Pattern " 20[2-3]\d{5} " "${scriptDir}\${scriptCmd}") -replace '.* (20[2-3]\d{5}) .*', '$1'
if (-not $curScriptDate) {
$curScriptDate = "19700101"
}
<# CHECK: logfile #>
if ($cfg.log) {
if ((Test-Variable "logFile") -and (&Test-Path $logFile)) {
try {
[IO.File]::OpenWrite($logFile).close()
$logFileOk = $true
} catch { $null }
}
}
<########>
<# HELP #>
<########>
if ($_Args -iMatch "[-/?]h") {
$_Header = ("{0} ({1}:{2})" -f "$scriptName", "$scriptCmd", "$curScriptDate")
Write-Host "`r`n$_Header"
Write-Host ("-" * $_Header.Length)"`r`n"
Write-Host "Installs latest available Chromium version"
Write-Host "Checks RSS feed from `"chromium.woolyss.com`" and GitHub API", "`r`n"
Write-Host "USAGE: $scriptCmd -[name|arch|channel|force] or -[list|crTask|shTask]", "`r`n"
Write-Host "`t", "-name option must be set to a release name: (default=Hibbiki)"
Write-Host "`t`t", " <Official|Hibbiki|Marmaduke|Ungoogled|justclueless|Eloston|RobRich>"
Write-Host "`t", "-channel can be set to [stable|dev] (default=stable)"
Write-Host "`t", "-arch can be set to [64bit|32bit] (default=64bit)", "`r`n"
Write-Host "`t", "-list show available releases and exit"
Write-Host "`t", "-crTask create a daily scheduled task and exit"
Write-Host "`t", "-shTask show scheduled task details and exit"
Write-Host "`t", "-force always (re)install, even if latest version is installed", "`r`n"
Write-Host "EXAMPLE: `".\$scriptCmd -name Marmaduke -arch 64bit -channel stable [-crTask]`"", "`r`n"
Write-Host "NOTES: Options `"name`" and `"channel`" need an argument (CasE Sensive)"
Write-Host "`t", "Try '$scriptCmd -advhelp' for `"advanced`" options", "`r`n"
exit 0
}
<# ADVANCED HELP #>
if ($_Args -iMatch "[-/?]ad?v?he?l?p?") {
$_Header = ("{0}: Advanced Options" -f "$scriptName")
Write-Host "`r`n$_Header"
Write-Host ("-" * $_Header.Length)"`r`n"
Write-Host "USAGE: $scriptCmd -[cAutoUp|cUpdate|appDir|linkArgs|proxy|sysLvl|ignVer|tag]"
Write-Host "`t`t", " -[tsMode|rmTask|noVbs|confirm]", "`r`n"
Write-Host "`t", "-cAutoUp auto update this script, set option to <0|1> (default=1)"
Write-Host "`t", "-cUpdate manually update this script to latest version and exit"
Write-Host "`t", "-proxy use a http proxy server, set option to <uri>", "`r`n"
Write-Host "`t", "-appDir (archives) extract to %AppData%\Chromium\Application\`$name"
Write-Host "`t", "-linkArgs (archives) sets Chromion shortcut to chrome.exe <arguments>", "`r`n"
Write-Host "`t", "-sysLvl system-level, install for all users on machine"
Write-Host "`t", "-ignVer ignore version mismatch between rss feed and filename"
Write-Host "`t", "-tag can be set to filter releases on matching `"<regex>`""
Write-Host "`t", " e.g. `"avx$`" note: use double quotes around regex", "`r`n"
Write-Host "`t", "-tsMode (task) scheduler mode, set to <1|2|3> (default=auto)"
Write-Host "`t", " option 1=normal:win8+ 2=legacy:win7 3=cmd:schtasks"
Write-Host "`t", "-rmTask (task) remove scheduled task and exit"
Write-Host "`t", "-noVbs (task) do not use vbs wrapper to hide tasks window"
Write-Host "`t", "-confirm (task) answer 'Y' on prompt about removing scheduled task"
exit 0
}
<####################>
<# HANDLE ARGUMENTS #>
<####################>
<# handle only 'flags' - no options that have args #>
foreach ($a in $_Args) {
$flags = "[-/](force|fakeVer|list|rss|crTask|rmTask|shTask|xmlTask|manTask|noVbs|confirm|scheduler|ignHash|cUpdate|appDir|sysLvl|ignVer)"
if ($match = $(Select-String -CaseSensitive -Pattern $flags -AllMatches -InputObject $a)) {
Invoke-Expression ('{0}="{1}"' -f ($match -replace "^-", "$"), 1);
$_Args = ($_Args) | Where-Object { $_ -ne $match }
}
}
<# handle options with args #>
if (($_Args.length % 2) -eq 0) {
$i = 0
While ($_Args -Is [Object[]] -and $i -lt $_Args.length) {
<# OLD: $i = 0; While ($i -lt $_Args.length) { #>
if ((($_Args[$i] -match "^-debug") -and ($_Args[($i + 1)] -match "^\d")) -or (($_Args[$i] -match "^-") -and ($_Args[($i + 1)] -match "^[\w\.]"))) {
Invoke-Expression ('{0}="{1}"' -f ($_Args[$i] -replace "^-", "$"), ($_Args[++$i] | Out-String).Trim());
}
$i++
}
} else {
Write-Host -ForegroundColor Red "Invalid option(s) specified (they're CasE Sensive)"
Write-Host -ForegroundColor Red "Try `"$scriptCmd -h`" for help, exiting..."
exit 1
}
<# SET: inline script config, overwrite any args from cli #>
<# editor arg (legacy) #>
if (!$name -and $editor) {
$name = $editor
}
if (!$name -and $cfg.name) {
$name = $cfg.name
}
<# editor cfg (legacy) #>
if ((!$name -and !$cfg.name) -and $cfg.editor) {
$name = $cfg.editor
}
if (!$channel -and $cfg.channel) {
$channel = $cfg.channel
}
if (!$arch -and $cfg.arch) {
$arch = $cfg.arch
}
if (!$proxy -and $cfg.proxy) {
$proxy = $cfg.proxy
}
if (!$cAutoUp -and ($cfg.cAutoUp -eq $true) -and (!$dotSourced)) {
$cAutoUp = 1
}
if ($cfg.linkArgs) {
$srcExeArgs = $cfg.linkArgs
}
if ($linkArgs) {
$srcExeArgs = $linkArgs
}
if ($ignhash) {
$script:ignHash = 1
}
if (!$vtApiKey -and $cfg.vtApiKey) {
$vtApiKey = $cfg.vtApiKey
}
if ($cfg.sysLvl) {
$sysLvl = $cfg.sysLvl
}
if (!$tag -and $cfg.tag) {
$tag = $cfg.tag
}
if ($proxy) {
$PSDefaultParameterValues.Add("Invoke-WebRequest:Proxy", "$proxy")
$webproxy = New-Object System.Net.WebProxy
$webproxy.Address = $proxy
}
<# CHECK: alias match, overrides var #>
if (Test-Variable "name") {
$items.GetEnumerator() | Where-Object { !$_.Value.disabled } | ForEach-Object {
if ($name -in $_.Value.alias) {
$name = $_.Key
}
}
}
@{ "32bit|32|x86" = "32-bit"; "64bit|64|x64" = "64-bit"; }.GetEnumerator() | ForEach-Object {
if ($_.Key -match $arch) {
$arch = $_.Value
}
}
<# SET: Chromium version from registry or path #>
if ($sysLvl -eq 1) {
$chrInstall = "System"
}
$versionRegKeys[$chrInstall].GetEnumerator() | ForEach-Object {
if (-not $curVersion) {
$curVersion = (Get-ItemProperty -EA 0 -WA 0 $_.name).$($_.value)
}
}
if (-not (Test-Variable "curVersion")) {
$versionPaths[$chrInstall] | ForEach-Object {
if ((-not $installPath) -and (&Test-Path $_)) {
$installPath = $_
}
}
$curVersion = (Get-ChildItem $installPath -EA 0 -WA 0 | Where-Object { $_.Name -match "\d\d.\d.\d{4}\.\d{1,3}" } ).Name |
Sort-Object | Select-Object -Last 1
}
<# SCRIPT FUNC: msg #>
function Write-Msg {
<#
.SYNOPSIS
Helper function to format and output (debug) messages
.NOTES
Place on top of main script, *before* first msg call
.PARAMETER options
dbg "DEBUG: some msg"
dbg, 1 if ($debug -ge 4) { "DEBUG:level 1" }
err "ERROR: some msg" (Red)
wrn "WARNING: some msg" (Yellow)
nnl NoNewLine
log log msg to file
tee log msg to file AND stdout
fgColor e.g. Blue
fgColor,bgColor e.g. White,DarkGray
.DESCRIPTION
Write-Msg [-o dbg,(int)lvl,err,wrn,log,nnl,tee,fgColor|fgColor,bgColor] "String"
.EXAMPLE
Write-Msg -o dbg, 1, Magenta, tee "some debugging text"
#>
[CmdletBinding()]
param (
[Alias("o")]
[ValidateScript({
if ("$_" -match "dbg|warn|err|nnl|log|tee|out|^[0-9]$|^(?-i:[A-Z][a-zA-Z]{2,})") {
$true
} else {
Throw "Invalid value is: `"$_`""
}
})]
$options,
[Parameter(Position = 1, ValueFromRemainingArguments = $true)]
[string]$msg
)
[bool]$dbg = [bool]$log = [bool]$tee = $false
[int]$lvl = 0
$msgParams = @{}
$cnt = 0
foreach ($opt in $options) {
switch -regex ($opt) {
'dbg' { $pf = "DEBUG: "; $dbg = $true; }
'warn' { $pf = "WARNING: "; $msgParams += @{ForegroundColor = "Yellow" } }
'err' { $pf = "ERROR: "; $msgParams += @{ForegroundColor = "Red" } }
'nnl' { $msgParams += @{NoNewLine = $true} }
'log' { $log = $true }
'tee' { $tee = $true }
'out' { $out = $true }
'^[0-9]$' { $lvl = $($matches[0]) }
'^(?-i:[A-Z][a-zA-Z]{2,})' {
if ($cnt -ge 1) {
$msgParams += @{BackgroundColor = $($matches[0]) }
} else {
$msgParams += @{ForegroundColor = $($matches[0]) }
}
$cnt++
}
}
}
if (!$log -and ((!$dbg) -or (($dbg) -and ($debug -ge $lvl)))) {
if ($msg.Split()[0] -eq "System.Object[]") {
$pf = "DEBUG[invalid_opts]: "
$s = $msg.Split()
$msg = $s[1..$s.Length]
}
if ($out) {
Write-Output @msgParams ("{0}$msg" -f $pf)
} else {
Write-Host @msgParams ("{0}$msg" -f $pf)
}
}
if ($logFileOk -and ($log -or $tee)) {
Add-Content $logFile -Value (((Get-Date).toString("yyyy-MM-dd HH:mm:ss")) + " $msg")
}
}
Write-Msg -o dbg, 1 "`$chrInstall=`"$chrInstall`""
<# SCRIPT FUNC: windows version #>
function Get-WinVer {
<#
.SYNOPSIS
Get Windows Version and supported Task Scheduler Mode
.NOTES
Place in main script *before* using 'tsMode' variable
#>
param(
[hashtable]$osInfo,
[int]$tsModeNum
)
[bool]$osFound = $false
[version]$osVersion = [System.Environment]::OSVersion.Version
[int]$osProdType = (Get-CIMInstance Win32_OperatingSystem).ProductType
[string]$osFullName = "Unknown Windows Version"
<# DEBUG: TEST WINVER
if ($debug -ge 3) {
[version]$osVersion = "6.1"; $osProdType = 3
[version]$osVersion = '10.0.22621.0'; $osProdType = 3
[version]$osVersion = '10.0.19042'; $osProdType = 3
[version]$osVersion = '10.0.20285'; $osProdType = 3
#>
$osInfo.winVer.GetEnumerator() | ForEach-Object {
if (-not $osFound) {
$compareVersion = ([version]("{0}.{1}" -f $osVersion.Major, $osVersion.Minor).ToString()).CompareTo(([version]("{0}.{1}" -f $_.Value[0..1])))
if ($compareVersion -eq 0 -and ($osVersion.Build -ge $_.Value[2]) -and ($osProdType -eq $_.Value[3])) {
$osFound = $true
$osFullName = ("`"{0}`" ({1}.{2}.{3}, {4})" -f $_.Key, $osVersion.Major, $osVersion.Minor, $osVersion.Build, $osInfo.osTypeName[$osProdType])
$osTsModeNum = $_.Value[4]
return $osFound, $osFullName, $osTsModeNum
}
}
} | Out-Null
if ($tsModeNum -notmatch '^[1-3]$') {
$tsModeNum = if ($osFound) { $osTsModeNum } else { 3 }
}
return @{
osFullName = $osFullName
tsMode = $tsModeNum
tsModeName = $osObj.taskModeName.$tsModeNum
}
}
[hashtable]$winVerResult = Get-WinVer -osInfo $osObj -tsModeNum $tsMode
$tsMode = $winVerResult.tsMode
<# OPTION: 'list' shows version, name, rss and exits #>
if ($list -eq 1) {
Write-Msg
Write-Msg -o nnl "Currently installed Chromium version: "
Write-Msg $curVersion
Write-Msg "`r`n"
Write-Msg "Available releases:"
$items.GetEnumerator() | `
Where-Object { $_.Value -and !$_.Value.disabled } | `
Sort-Object -Property Name | `
Format-Table @{l = 'Name'; e = { $_.Key } }, `
@{l = 'Website'; e = { $_.Value.url } }, `
@{l = 'Repository'; e = { $_.Value.repo } }, `
@{l = 'Filemask'; e = { $_.Value.filemask } }
<# Write-Msg "Available from Woolyss RSS Feed:"
$xml = [xml](Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 -Uri "https://chromium.woolyss.com/feed/windows-$($arch)")
$xml.rss.channel.Item | Select-Object @{N = 'Title'; E = 'title' }, @{N = 'Link'; E = 'link' } | Out-String #>
exit 0
}
<# CHECK: mandatory and user args #>
if (-not ($items.Keys -ceq $name)) {
Write-Msg -o err "Name setting incorrect `"$name`" (CasE Sensive). Exiting ..."
exit 1
} else {
$items.GetEnumerator() | ForEach-Object {
if ($_.Name -ceq $name) {
if ($_.Value.disabled) {
Write-Msg -o err "Release is disabled. Exiting ..."
exit 1
}
if ($_.Value.fmt -cnotmatch"^(XML|JSON)$") {
Write-Msg -o err "Invalid format `"${items[$_.Name].fmt}`", must be `"XML`" or `"JSON`". Exiting ..."
exit 1
}
}
}
}
if ($arch -cnotmatch"^(32-bit|64-bit)$") {
$arch = "64-bit"
Write-Msg "Using default architecture (64-bit)"
}
if ($channel -cnotmatch"^(stable|dev)$") {
$channel = "stable"
Write-Msg "Using default channel (`"stable`")"
}
if ($cAutoUp -notmatch "^(0|1)$") {
Write-Msg -o warn, tee "Invalid AutoUpdate setting `"$cAutoUp`", must be 0 or 1"
}
<# SCRIPT FUNC: update #>
function Split-Script ($content) {
<#
.SYNOPSIS
Splits header and config from script content
.INPUTS
$content Array of strings/lines (do not use filename)
.OUTPUTS
$result Object or Boolean $false
#>
[int]$lnCfgStart = ($content | Select-String -Pattern "<# CONFIGURATION:? \s+ #>").LineNumber
[int]$lnCfgEnd = ($content | Select-String -Pattern "<# END OF CONFIGURATION ?[#-]+ ?#>").LineNumber
[hashtable]$result = @{}
if (($lnCfgStart -gt 1) -and ($lnCfgEnd -gt 1)) {
[object]$result.head = $content | Select-Object -Index (0..(${lnCfgStart} - 2))
[object]$result.config = $content | Select-Object -Index ((${lnCfgStart} - 1)..$(${lnCfgEnd} - 1))
[int]$lineCount = ($content).Count
[string]$lastLine = $content | Select-Object -Skip (${lineCount} - 1)
if ($lineCount -and $lastLine -eq "") {
[int]$lineCount = ${lineCount} - 2
}
[object]$result.script = $content | Select-Object -Index ($lnCfgEnd..$lineCount)
[string]$result.hash = (Get-FileHash -Algorithm SHA256 -InputStream ([System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes((($result.script)))))).Hash
} else {
return $false
}
return $result
}
function Update-ChrScript () {
return
<#
.SYNOPSIS
Compare date and version, update if available
.NOTES
REMOTE : README.md "Latest version: YYYYMMMDD"
LOCAL : chrupd.cmd " 20[2-3]\d{5} " (e.g. 20201231)
#>
[hashtable]$cmdParams = @{}
<# TEST: $cmdParams += @{ Verbose = $true } #>
if ($debug -ge 1) {
$cmdParams += @{ WhatIf = $true }
Write-Msg -o dbg, 1, Yellow "Update-ChrScript debug=`"$debug`" (!) NOT CHANGING FILES"
}
<# get date/version from readme #>
[System.Net.ServicePointManager]::SecurityProtocol = @("Tls13", "Tls12", "Tls11", "Tls")
[string]$ghApiUrl = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("aHR0cHM6Ly9hcGkuZ2l0aHViLmNvbS9yZXBvcy9ta29ydGhvZi9jaHJ1cGQ="))
<# skip api req when dot sourced or debugging, so we dont hit api rate limit #>
if (!$dotSourced -and ($debug -eq 0)) {
[pscustomobject]$ghReadmeObj = (
ConvertFrom-Json(Invoke-WebRequest -UseBasicParsing -TimeoutSec 300 -Uri "$ghApiUrl/contents/README.md")
)
} else {
<# TEST: fake new version = ghReadmeObj_20291231.json, old version = ghReadmeObj_20211002.json)) #>
Write-Msg -o dbg, 1 "Update-ChrScript TEST MODE"
[pscustomobject]$ghReadmeObj = (
ConvertFrom-Json(Get-Content .\test\data\ghReadme_20291231.json)
)
}
[string]$ghReadmeContent = [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String((($ghReadmeObj).content)))) -split "`r?`n"
[string]$newDate = ($ghReadmeContent | Select-String -Pattern "Latest version.* 20[2-3]\d{5} ") -replace '.*Latest version: (20[2-3]\d{5}) .*', '$1'
Write-Msg -o dbg, 1 "Update-ChrScript curScriptDate=`"$curScriptDate`" newDate=`"$newDate`""
<# compare date in remote 'README.md' with local 'chrupd.cmd' #>
if ($newDate -and (([DateTime]::ParseExact($newDate, 'yyyyMMdd', $null)) -gt ([DateTime]::ParseExact($curScriptDate, 'yyyyMMdd', $null)))) {
Write-Msg -o tee "New chrupd version `"$newDate`" available, updating script..."
Write-Msg
<# SPLIT: current script file #>
Write-Msg -o dbg, 1 "Update-ChrScript Split-Script `$scriptCmd=`"$scriptCmd`""
$localSplit = Split-Script $(Get-Content "${scriptDir}\${scriptCmd}")
<# SPLIT: new script content from github #>
Write-Msg -o dbg, 1 "Update-ChrScript getting chrupd contents from api.github.com"
[pscustomobject]$ghScriptObj = (
ConvertFrom-Json(
Invoke-WebRequest -UseBasicParsing -TimeoutSec 300 -Uri "$ghApiUrl/contents/chrupd.cmd"
)
)
$ghScriptContent = [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String((($ghScriptObj).content)))) -split "`r?`n"
Write-Msg -o dbg, 1 "Update-ChrScript Split-Script `"`$ghScriptContent`""
if ($debug -ge 1) {
Split-Script $ghScriptContent | Out-Null
}
if ($ghScriptContent) {
$ghSplit = Split-Script $ghScriptContent
} else {
Write-Msg -o err, tee "Could not download new script, skipped update"
break
}
<# write new script, merge current local config if found #>
if ($ghSplit) {
if ($localSplit) {
$newContent = $ghSplit.head, $localSplit.config, $ghSplit.script
Write-Msg -o dbg, 1 "Update-ChrScript localSplit.hash=`"$($localSplit.hash)`""
Write-Msg -o dbg, 1 "Update-ChrScript ghSplit.hash=`"$($localSplit.hash)`""
} else {
$newContent = $ghScriptContent
Write-Msg -o warn "Current script configuration not found, using defaults"
}
if ( $(try { (&Test-Path "${scriptDir}\${scriptCmd}.tmp") } catch { $false }) ) {
Write-Msg -o dbg, 1 "${scriptCmd}.tmp already exists, removing..."
try {
Remove-Item @cmdParams -ErrorAction 1 -WarningAction 1 "${scriptDir}\${scriptCmd}.tmp" -Force
} catch {
Write-Msg -o err, tee "Could not remove ${scriptCmd}.tmp"
break
}
}
try {
Set-Content @cmdParams -EA 1 -WA 1 "${scriptDir}\${scriptCmd}.tmp" -Value $newContent
} catch {
Write-Msg -o err, tee "Could not write script, skipped update"
break
}
<# replace 'in use' script only if we're running as ps1 (.\chrupd.ps1) #>
if ($scriptCmd.Split(".")[1] -eq "ps1") {
try {
Move-Item @cmdParams -Force -EA 0 -WA 0 -Path "${scriptDir}\${scriptCmd}" -Destination "${scriptDir}\${scriptCmd}.bak"
} catch {
Write-Msg -o err, tee "Could not move `"${scriptCmd}`" to `"$contentCmd.bak`""
break
}
try {
Move-Item @cmdParams -Force -EA 0 -WA 0 -Path "${scriptDir}\${scriptCmd}.tmp" -Destination "${scriptDir}\${scriptCmd}"
} catch {
Write-Host -o err, tee "Could not move `"${scriptCmd}.tmp`" to `"$contentCmd`""
break
}
}
} else {
Write-Msg -o err, tee "Unable to get new script, skipped update"
break
}
} else {
if ($cUpdate) {
Write-Msg "No script updates available"
Write-Msg
} else {
Write-Msg -o dbg, 1 "Update-ChrScript cUpdate=`"$cUpdate`" no updates available"
}
}
}
<# OPTION: update script and exit #>
if ($cUpdate) {
Update-ChrScript
Exit
}
<# OPTION: auto update #>
if ($cAutoUp -eq 1) {
Update-ChrScript
}
<###################>
<# SCHEDULED TASKS #>
<###################>
<# 1) Normal (Windows 8+), uses Cmdlets [default] #>
<# 2) Legacy (Windows 7), uses COM object #>
<# 3) Command (Windows XP), uses schtasks.exe #>
<# TASK: vars #>
$confirmParam = $true
if (-not (Test-Variable "tsMode")) {
$tsMode = 1
}
[string]$vbsWrapper = $scriptDir + "\chrupd.vbs"
[string]$taskArgs = "-scheduler -name $name -arch $arch -channel $channel -cAutoUp $cAutoUp"
if ($proxy) {
$taskArgs += " -proxy $proxy "
}
if ($tag) {
$taskArgs += " -tag $tag "
}
if ($noVbs -eq 0) {
[string]$taskCmd = "$vbsWrapper"
} else {
[string]$taskCmd = 'powershell.exe'
[string]$taskArgs = "-ExecutionPolicy ByPass -NoLogo -NoProfile -WindowStyle Hidden $scriptCmd $taskArgs"
}
<# XXX: Alternative to hide window
https://github.com/PowerShell/PowerShell/issues/3028
cmd.exe /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ". 'C:\path\test.ps1'" #>
<# TASK: VBS WRAPPER #>
$vbsContent = @"
'
' Wrapper for chrupd.cmd to hide window when using Task Scheduler
'
Dim WinScriptHost
For i = 0 to (WScript.Arguments.Count - 1)
Args = Args & " " & WScript.Arguments(i)
Next
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "${scriptDir}\\${scriptCmd}" & Chr(34) & " " & Args, 0
Set WinScriptHost = Nothing
"@
<# TASK: XML #>
$xmlContent = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Description>$($taskMsg.descr)</Description>
<URI>\${scriptName}</URI>
</RegistrationInfo>
<Principals>
<Principal id="Author">
<LogonType>InteractiveToken</LogonType>
</Principal>
</Principals>
<Settings>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<IdleSettings>
<Duration>PT10M</Duration>
<WaitTimeout>PT1H</WaitTimeout>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
</Settings>
<Triggers>
<CalendarTrigger>
<StartBoundary>2018-10-13T17:00:00+02:00</StartBoundary>
<RandomDelay>PT1H</RandomDelay>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Actions Context="Author">
<Exec>
<Command>${taskCmd}</Command>
<Arguments>${taskArgs}</Arguments>
<WorkingDirectory>${scriptDir}</WorkingDirectory>
</Exec>
</Actions>
</Task>
"@
<# CRTASK: create scheduled task #>
if ($crTask -eq 1) {
if ( $(try { -not (&Test-Path $vbsWrapper) } catch { $false }) ) {
Write-Msg "VBS Wrapper ($vbsWrapper) missing, creating...`r`n"
Set-Content $vbsWrapper -ErrorAction Stop -WarningAction Stop -Value $vbsContent
if ( $(try { -not (&Test-Path $vbsWrapper) } catch { $false }) ) {
Write-Msg "Could not create VBS Wrapper, try again or use `"-noVbs`" to skip"
exit 1
}
}
switch ($tsMode) {
1 { <# crtask: 1 normal mode #>
$action = New-ScheduledTaskAction -Execute $taskCmd -Argument "$taskArgs" -WorkingDirectory "$scriptDir"
$trigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Hour 1) -Daily -At 17:00
if (-not (&Get-ScheduledTask -EA 0 -TaskName "$scriptName")) {
Write-Msg "$($taskMsg.create -f "$scriptName")"
try { (Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "$scriptName" -Description "$($taskMsg.descr)") | Out-Null }
catch { Write-Msg "$($taskMsg.problem)`r`nERROR: `"$($_.Exception.Message)`"" }
} else {
Write-Msg $taskMsg.exists
}
if (&Get-ScheduledTask -EA 0 -TaskName "$scriptName" -OutVariable task) {
if (Test-Variable "task") {
Write-Msg ("Task: `"{0}{1}`"`r`nDescription: `"{2}`", State: {3}`r`n" -f ($task).TaskPath, ($task).TaskName, ($task).Description, ($task).State)
} else {
Write-Msg $taskMsg.failed
}
} else {
Write-Msg ("{0}`r`n`r`n {1}`r`n {2}`r`n" -f $taskMsg.failed, $($taskMsg.manual -f $scriptCmd), $($taskMsg.export -f $scriptCmd))
}
}
2 { <# crtask: 2 legacy mode #>
$taskService = New-Object -ComObject("Schedule.Service")
$taskService.Connect()