-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathvm.common.psm1
executable file
·1915 lines (1716 loc) · 67.9 KB
/
vm.common.psm1
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
# Setting this to "Stop". Functions should properly handle errors or throw to calling function.
$ErrorActionPreference = 'Stop'
# ################################################################################################ #
# \ \ ---------------------------------------- N O T E ---------------------------------------- / /
#
# Below are general helper functions for any VM package to use
#
# ################################################################################################ #
function VM-ConvertFrom-Json([object] $item) {
<#
.SYNOPSIS
Convert a JSON string into a hash table
.DESCRIPTION
Convert a JSON string into a hash table, without any validation
.OUTPUTS
[hashtable] or $null
#>
Add-Type -Assembly system.web.extensions
$ps_js = New-Object system.web.script.serialization.javascriptSerializer
try {
$result = $ps_js.DeserializeObject($item)
} catch {
$result = $null
}
# Cast dictionary to hashtable
[hashtable] $result
}
function VM-Remove-PreviousZipPackage {
<#
.DESCRIPTION
Remove files from previous zips for upgrade. They should be listed in a *.txt file.
If no expression is provided, it will look for files matching: *.zip.txt and *.7z.txt
.PARAMETER packagePath
Path to the chocolatey package (usually %PROGRAMDATA%\Chocolatey\lib\<package_name>)
.PARAMETER expression
[OPTIONAL] A wildcard expression for a file type containing a list of files to delete.
#>
param(
[Parameter(Mandatory=$true, Position=0)]
[string] $packagePath,
[Parameter(Mandatory=$false)]
[string] $expression=$null
)
if ($expression) {
$previousZipFiles = Get-ChildItem -Path (Join-Path $packagePath $expression)
} else {
$previousZipFiles = Get-ChildItem -Path (Join-Path $packagePath "*.zip.txt"), (Join-Path $packagePath "*.7z.txt")
}
foreach ($zipFileName in $previousZipFiles) {
if ((Test-Path -Path $zipFileName)) {
$zipContents = @(Get-Content $zipFileName -Force)
if ($zipContents) {
foreach ($fileInZip in $zipContents) {
if (($null -ne $fileInZip) -AND ($fileInZip.Trim() -ne '') -AND (Test-Path $fileInZip)) {
Remove-Item -Path $fileInZip -Recurse -Force -ea 0
}
}
}
}
}
}
function VM-Write-Log {
<#
.SYNOPSIS
Log message to file and console.
.DESCRIPTION
Log message to log file with extra useful information and to console with a color depending on the level.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, Position=0)]
[ValidateSet("INFO","WARN","ERROR")]
[String] $level,
[Parameter(Mandatory=$true, Position=1)]
[string] $message
)
# Get log file
$envVarName = "VM_COMMON_DIR"
$commonDirPath = [Environment]::GetEnvironmentVariable($envVarName, 2)
$logFile = Join-Path $commonDirPath "log.txt"
# If log file doesn't exist, create it
if (-Not (Test-Path $logFile)) {
New-Item -Path $logFile -ItemType file -Force | Out-Null
}
# Log message to file
$stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
try {
$scriptName = Split-Path -Path $MyInvocation.ScriptName -Leaf
if ((${Env:chocolateyPackageFolder}) -AND (Test-Path env:\"chocolateyPackageFolder")) {
$choco_dir = Split-Path -Path ${Env:chocolateyPackageFolder} -Leaf
$line = "$stamp [$choco_dir] $scriptName [+] $level : $message"
} else {
$line = "$stamp $scriptName [+] $level : $message"
}
} catch {
$line = "$stamp [+] $level : $message"
}
Add-Content $logfile -Value $line
# Log message to console
if (($level -eq "ERROR") -Or ($level -eq "FATAL")) {
Write-Host -ForegroundColor Red -BackgroundColor White "$message"
} elseif ($level -eq "WARN") {
Write-Host -ForegroundColor Yellow "$message"
} else {
Write-Host -ForegroundColor Cyan "$message"
}
}
function VM-Assert-Path {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String] $path
)
if (-Not (Test-Path $path)) {
$err_msg = "Invalid path: $path"
VM-Write-Log "ERROR" $err_msg
throw $err_msg
}
}
# Raise an exception if the signtool.exe is not found or if the signature of $filePath is invalid
# vcbuildtools.vm installs signtool.exe
function VM-Assert-Signature {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String] $filePath
)
$signtoolPath = Get-ChildItem -Path "C:\Program Files*\Windows Kits\10\bin\*\x86\signtool.exe" | Select-Object -Last 1
if (-Not $signtoolPath) { throw "signtool.exe not found" }
& $signtoolPath verify /pa /all /tw /q $filePath
if ($LASTEXITCODE) {
throw "INVALID SIGNATURE: $filePath"
}
}
function VM-Get-DiskSize {
$diskdrive = "${Env:SystemDrive}"
$driveName = $diskdrive.substring(0, $diskdrive.length-1)
$disk = Get-PSDrive "$driveName"
$disksize = (($disk.used + $disk.free)/1GB)
return $disksize
}
function VM-Get-FreeSpace {
[double]$freeSpace = 0.0
[string]$wql = "SELECT * FROM Win32_LogicalDisk WHERE MediaType=12"
$drives = Get-CIMInstance -query $wql
if($null -ne $drives) {
foreach($drive in $drives) {
$freeSpace += ($drive.freeSpace)
}
}
return ($freeSpace / 1GB)
}
function VM-Check-Reboot {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String] $package
)
try {
if (Test-PendingReboot){
VM-Write-Log "ERROR" "Host must be rebooted before continuing installation of $package.`n"
Invoke-Reboot
exit 1
}
} catch {
continue
}
}
function VM-New-Install-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String] $dir
)
VM-Assert-Path $dir
$outputFile = Join-Path $dir "install_log.txt"
if (-Not (Test-Path $outputFile)) {
New-Item -Path $outputFile -Force | Out-Null
}
$(Get-Date -f o) | Out-File -FilePath $outputFile -Append
return $outputFile
}
function VM-Install-Shortcut{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$false, Position=2)]
[string] $executablePath,
[Parameter(Mandatory=$false)]
[bool] $consoleApp=$false,
[Parameter(Mandatory=$false)]
[switch] $powershell,
[Parameter(Mandatory=$false)]
[switch] $runAsAdmin,
[Parameter(Mandatory=$false)]
[string] $executableDir,
[Parameter(Mandatory=$false)]
[string] $arguments = "",
[Parameter(Mandatory=$false)]
[string] $iconLocation
)
$shortcutDir = Join-Path ${Env:TOOL_LIST_DIR} $category
$shortcut = Join-Path $shortcutDir "$toolName.lnk"
# Set the default icon to be the executable's icon
if (-Not $iconLocation) {$iconLocation = $executablePath}
if (-not $executableDir) {
$executableDir = Join-Path ${Env:UserProfile} "Desktop"
}
VM-Assert-Path $executableDir
if ($consoleApp -or $powershell) {
if ($consoleApp) {
$executableCmd = Join-Path ${Env:WinDir} "system32\cmd.exe" -Resolve
# Change to executable dir, print command to execute, and execute command
$executableArgs = "/K `"cd `"$executableDir`" && echo $executableDir^> $executablePath $arguments && `"$executablePath`" $arguments`""
} else {
$executableCmd = Join-Path "${PSHome}" "powershell.exe" -Resolve
$executableArgs = "-ExecutionPolicy Bypass -NoExit -Command `"`$cmd = '$arguments'; Write-Host PS $executableDir ``> `$cmd; Invoke-Expression `$cmd`""
$iconLocation = $executableCmd
}
$shortcutArgs = @{
ShortcutFilePath = $shortcut
TargetPath = $executableCmd
Arguments = $executableArgs
WorkingDirectory = $executableDir
IconLocation = $iconLocation
}
if ($runAsAdmin) {
$shortcutArgs.RunAsAdmin = $true
}
Install-ChocolateyShortcut @shortcutArgs
} else {
$shortcutArgs = @{
ShortcutFilePath = $shortcut
TargetPath = $executablePath
Arguments = $arguments
WorkingDirectory = $executableDir
IconLocation = $iconLocation
}
if ($runAsAdmin) {
$shortcutArgs.RunAsAdmin = $true
}
Install-ChocolateyShortcut @shortcutArgs
}
VM-Assert-Path $shortcut
# If the targets is a .bat file, change the shortcut icon to Windows default
$extension = [System.IO.Path]::GetExtension($executablePath)
if ($extension -eq ".bat") {
$Shell = New-Object -ComObject ("WScript.Shell")
$Shortcut = $Shell.CreateShortcut($shortcut)
$IconArrayIndex = -68 # This is the specific icon that Windows uses for .bat files by default
$IconLocation = "C:\WINDOWS\system32\imageres.dll"
$Shortcut.IconLocation = "$IconLocation,$IconArrayIndex"
$Shortcut.Save()
}
}
function VM-Get-IDA-Plugins-Dir {
return New-Item "$Env:APPDATA\Hex-Rays\IDA Pro\plugins" -ItemType "directory" -Force
}
# Downloads an IDA plugin file or ZIP containing a plugin (and supporting files/directories) to the plugins directory.
# For ZIPs, we check if there is an inner folder (this is the case for GH ZIPs) and if there is a directory called 'plugins'.
# We copy all files in this directory with the exception of the README and the LICENSE file (often present in GH repos).
# The copied files must include $pluginName.
function VM-Install-IDA-Plugin {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param
(
[Parameter(Mandatory=$true)]
[string] $pluginName, # Example: capa_explorer.py
[Parameter(Mandatory=$true)]
[string] $pluginUrl,
[Parameter(Mandatory=$true)]
[string] $pluginSha256
)
try {
$pluginExtension = [System.IO.Path]::GetExtension($pluginUrl)
$pluginsDir = VM-Get-IDA-Plugins-Dir
$pluginPath = Join-Path $pluginsDir $pluginName
if ($pluginExtension -eq ".zip") {
$tempDownloadDir = Join-Path ${Env:chocolateyPackageFolder} "temp_$([guid]::NewGuid())"
# Download and unzip
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
unzipLocation = $tempDownloadDir
url = $pluginUrl
checksum = $pluginSha256
checksumType = 'sha256'
}
Install-ChocolateyZipPackage @packageArgs | Out-Null
VM-Assert-Path $tempDownloadDir
# Check if there is inner folder (for example for ZIPs downloaded from GH)
$childItems = Get-ChildItem $tempDownloadDir -ea 0
if (($childItems).Count -eq 1) {
$subDir = Join-Path $tempDownloadDir $childItems
if (Test-Path $subDir -PathType Container) {
$tempDownloadDir = $subDir
}
}
# Look for the plugins directory
$pluginDir = Get-Item "$tempDownloadDir\plugins" -ea 0
if (!$pluginDir) { $pluginDir = $tempDownloadDir }
# Delete files we don't want to copy
Remove-Item "$pluginDir\README*" -Force -ea 0
Remove-Item "$pluginDir\LICENSE*" -Force -ea 0
Copy-Item "$pluginDir\*" $pluginsDir -Recurse
}
else {
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
url = $pluginUrl
checksum = $pluginSha256
checksumType = "sha256"
fileFullPath = $pluginPath
forceDownload = $true
}
Get-ChocolateyWebFile @packageArgs
}
VM-Assert-Path $pluginPath
} catch {
VM-Write-Log-Exception $_
}
}
# Removes an IDA plugin file from the plugins directory
function VM-Uninstall-IDA-Plugin {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param
(
[Parameter(Mandatory=$true)]
[string] $pluginName # Example: capa_explorer.py
)
$pluginPath = Join-Path (VM-Get-IDA-Plugins-Dir) $pluginName
Remove-Item $pluginPath -Recurse -Force -ea 0
}
# This functions returns $toolDir and $executablePath
function VM-Install-From-Zip {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[string] $zipUrl,
[Parameter(Mandatory=$false, Position=3)]
[string] $zipSha256,
[Parameter(Mandatory=$false)]
[string] $zipUrl_64,
[Parameter(Mandatory=$false)]
[string] $zipSha256_64,
[Parameter(Mandatory=$false)]
[bool] $consoleApp=$false,
[Parameter(Mandatory=$false)]
[bool] $innerFolder=$false, # Subfolder in zip with the app files
[Parameter(Mandatory=$false)]
[string] $arguments = "",
[Parameter(Mandatory=$false)]
[string] $executableName, # Executable name, needed if different from "$toolName.exe"
[Parameter(Mandatory=$false)]
[switch] $verifySignature,
[Parameter(Mandatory=$false)]
[switch] $withoutBinFile, # Tool should not be installed as a bin file
# Examples:
# $powershellCommand = "Get-Content README.md"
# $powershellCommand = "Import-Module module.ps1; Get-Help Main-Function"
[Parameter(Mandatory=$false)]
[string] $powershellCommand
)
try {
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
# Remove files from previous zips for upgrade
VM-Remove-PreviousZipPackage ${Env:chocolateyPackageFolder}
# We do not check hashes for tools that we use signature verification for
if ($verifySignature) {
# Download zip
$packageArgs = @{
packageName = $env:ChocolateyPackageName
file = Join-Path ${Env:TEMP} $toolName
url = $zipUrl
}
$filePath = Get-ChocolateyWebFile @packageArgs
# Extract zip
Get-ChocolateyUnzip -FileFullPath $filePath -Destination $toolDir
}
else { # Not verifying signature, so check if hash is as expected
# Download and unzip
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
unzipLocation = $toolDir
url = $zipUrl
checksum = $zipSha256
checksumType = 'sha256'
url64bit = $zipUrl_64
checksum64 = $zipSha256_64
}
Install-ChocolateyZipPackage @packageArgs | Out-Null
}
VM-Assert-Path $toolDir
# If $innerFolder is set to $true, after unzipping there should be only one folder
# GitHub ZIP files typically unzip to a single folder that contains the tools.
if ($innerFolder) {
$dirList = Get-ChildItem $toolDir -Directory
$toolDir = Join-Path $toolDir $dirList[0].Name -Resolve
}
if ($verifySignature) {
# Check signature of all executable files individually
Get-ChildItem -Path "$toolDir\*.exe" | ForEach-Object {
try {
# Check signature for each file
VM-Assert-Signature $_.FullName
} catch {
# Remove the file with invalid signature
Write-Warning "Removing file '$($_.FullName)' due to invalid signature"
Remove-Item $_.FullName -Force -ea 0 | Out-Null
VM-Write-Log-Exception $_
}
}
}
if ($powershellCommand) {
$executablePath = $toolDir
VM-Install-Shortcut -toolName $toolName -category $category -arguments $powershellCommand -executableDir $executablePath -powershell
}
elseif ($withoutBinFile) { # Used when tool does not have an associated executable
if (-Not $executableName) { # Tool is located in $toolDir (c3.vm for example)
$executablePath = $toolDir
} else { # Tool is in a specific directory (pma-labs.vm for example)
$executablePath = Join-Path $toolDir $executableName -Resolve
}
VM-Install-Shortcut -toolName $toolName -category $category -executablePath $executablePath
}
else {
if (-Not $executableName) { $executableName = "$toolName.exe" }
$executablePath = Join-Path $toolDir $executableName -Resolve
VM-Install-Shortcut -toolName $toolName -category $category -executablePath $executablePath -consoleApp $consoleApp -arguments $arguments
Install-BinFile -Name $toolName -Path $executablePath
}
return ,@($toolDir, $executablePath)
} catch {
VM-Write-Log-Exception $_
}
}
function VM-Install-Node-Tool {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$false)]
[string] $arguments
)
try {
npm install -g $toolName --no-update-notifier
VM-Install-Shortcut -toolName $toolName -category $category -arguments "$toolName $arguments" -powershell
} catch {
VM-Write-Log-Exception $_
}
}
function VM-Install-Node-Tool-From-Zip {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[string] $zipUrl,
[Parameter(Mandatory=$false, Position=3)]
[string] $zipSha256,
# node command such as "jailme.js -h -b list"
[Parameter(Mandatory=$true)]
[string] $command,
[Parameter(Mandatory=$false)]
[bool] $innerFolder=$true # Default to true as most node apps are GH repos (ZIP with inner folder)
)
$toolDir = (VM-Install-From-Zip $toolName $category $zipUrl $zipSha256 -innerFolder $innerFolder -powershellCommand "node $command")[0]
# Install tool dependencies with npm
Set-Location $toolDir; npm install --no-update-notifier
}
# This functions returns $executablePath
function VM-Install-Single-Exe {
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[string] $exeUrl,
[Parameter(Mandatory=$false)]
[string] $exeSha256,
[Parameter(Mandatory=$false)]
[string] $exeUrl_64,
[Parameter(Mandatory=$false)]
[string] $exeSha256_64,
[Parameter(Mandatory=$false)]
[bool] $consoleApp=$false,
[Parameter(Mandatory=$false)]
[string] $arguments = ""
)
try {
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
# Get the file extension from the URL
$ext = (Split-Path -Path $exeUrl -Leaf).Split(".")[-1]
# Download and install
$executablePath = Join-Path $toolDir "$toolName.$ext"
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
url = $exeUrl
checksum = $exeSha256
checksumType = "sha256"
url64bit = $exeUrl_64
checksum64 = $exeSha256_64
fileFullPath = $executablePath
forceDownload = $true
}
Get-ChocolateyWebFile @packageArgs
VM-Assert-Path $executablePath
VM-Install-Shortcut -toolName $toolName -category $category -executableDir $toolDir -executablePath $executablePath -consoleApp $consoleApp -arguments $arguments
Install-BinFile -Name $toolName -Path $executablePath
return $executablePath
} catch {
VM-Write-Log-Exception $_
}
}
# This functions returns $scriptPath
function VM-Install-Single-Ps1 {
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[string] $ps1Url,
[Parameter(Mandatory=$false)]
[string] $ps1Sha256,
[Parameter(Mandatory=$false)]
[string] $ps1Url_64,
[Parameter(Mandatory=$false)]
[string] $ps1Sha256_64,
[Parameter(Mandatory=$false)]
[string] $ps1Cmd
)
try {
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
# Download and install
$scriptPath = Join-Path $toolDir "$toolName.ps1"
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
url = $ps1Url
checksum = $ps1Sha256
checksumType = "sha256"
url64bit = $ps1Url_64
checksum64 = $ps1Sha256_64
fileFullPath = $scriptPath
forceDownload = $true
}
Get-ChocolateyWebFile @packageArgs
VM-Assert-Path $scriptPath
VM-Install-Shortcut -toolName $toolName -category $category -executableDir $toolDir -arguments $ps1Cmd -powershell
return $scriptPath
} catch {
VM-Write-Log-Exception $_
}
}
function VM-Uninstall {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category
)
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
# Remove tool files
Remove-Item $toolDir -Recurse -Force -ea 0 | Out-Null
# Remove tool shortcut
VM-Remove-Tool-Shortcut $toolName $category
# Uninstall binary
Uninstall-BinFile -Name $toolName
# Refresh Desktop, needed for example if shortcut is used in FLARE-VM LayoutModification.xml
VM-Refresh-Desktop
}
function VM-Remove-Tool-Shortcut {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $shortcutName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category
)
$shortcutDir = Join-Path ${Env:TOOL_LIST_DIR} $category
$shortcut = Join-Path $shortcutDir "$shortcutName.lnk"
Remove-Item $shortcut -Force -ea 0 | Out-Null
}
# Delete Desktop shortcuts
function VM-Remove-Desktop-Shortcut {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName
)
# Some shortcuts exist in Public and/or User profiles.
ForEach ($location in @(${Env:Public}, ${Env:UserProfile})) {
$desktopShortcut = Join-Path $location "Desktop\$toolName.lnk"
if (Test-Path $desktopShortcut) {
Remove-Item $desktopShortcut -Force -ea 0
}
}
}
function VM-Install-With-Installer {
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[ValidateSet("EXE", "MSI")]
[string] $fileType,
[Parameter(Mandatory=$true, Position=3)]
# Some general silent args:
# $silentArgs = '/qn /norestart' # MSI
# $silentArgs = '/S' # NSIS
# $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' # Inno Setup
# Can also specify an install directory for Inno Setup via /DIR=`"<path>`"
# $silentArgs = '/s' # InstallShield
# $silentArgs = '/s /v"/qn"' # InstallShield with MSI
# $silentArgs = '/s' # Wise InstallMaster
# $silentArgs = '-s' # Squirrel
# $silentArgs = '-q' # Install4j
# $silentArgs = '-s -u' # Ghost
[string] $silentArgs,
[Parameter(Mandatory=$true, Position=4)]
[string] $executablePath,
[Parameter(Mandatory=$true, Position=5)]
[string] $url,
[Parameter(Mandatory=$false)]
[string] $sha256,
[Parameter(Mandatory=$false)]
[array] $validExitCodes= @(0, 3010, 1603, 1605, 1614, 1641),
[Parameter(Mandatory=$false)]
[bool] $consoleApp=$false,
[Parameter(Mandatory=$false)]
[string] $arguments = "",
[Parameter(Mandatory=$false)]
[string] $iconLocation
)
try {
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
# Get the file extension from the URL
$installerName = Split-Path -Path $url -Leaf
$ext = $installerName.Split(".")[-1].ToLower()
# Download and install
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
url = $url
checksum = $sha256
checksumType = "sha256"
}
if ($ext -in @("zip", "7z")) {
VM-Remove-PreviousZipPackage ${Env:chocolateyPackageFolder}
$unzippedDir= Join-Path $toolDir "$($toolName)_installer"
$packageArgs['unzipLocation'] = $unzippedDir
Install-ChocolateyZipPackage @packageArgs
VM-Assert-Path $unzippedDir
$exePaths = Get-ChildItem $unzippedDir | Where-Object { $_.Name.ToLower() -match '^.*\.(exe|msi)$' }
if ($exePaths.Count -eq 1) {
$installerPath = $exePaths[0].FullName
} else {
$exePaths = Get-ChildItem $unzippedDir | Where-Object { $_.Name.ToLower() -match '^.*(setup|install).*\.(exe|msi)$' }
if ($exePaths.Count -eq 1) {
$installerPath = $exePaths[0].FullName
} else {
throw "Unable to determine installer file within: $unzippedDir"
}
}
} else {
$installerPath = Join-Path $toolDir $installerName
$packageArgs['fileFullPath'] = $installerPath
Get-ChocolateyWebFile @packageArgs
VM-Assert-Path $installerPath
}
# Install tool via native installer
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
fileType = $fileType
file = $installerPath
silentArgs = $silentArgs
validExitCodes= $validExitCodes
softwareName = $toolName
}
Install-ChocolateyInstallPackage @packageArgs
VM-Assert-Path $executablePath
# if no icon path provided, set the shortcut icon to be the executable's icon. For MSI files, attempt to get executable icon from the installer first.
if (-Not $iconLocation) {
if ($fileType -eq 'MSI') {
$iconPath = VM-Get-MSIInstallerPathByProductName $toolName
if ($iconPath) {
$files = Get-ChildItem -Path $iconPath -Filter "*.ico"
if ($files.Count -gt 0) {
$iconLocation = Join-Path $iconPath $files[0]
}
}
# If no icon found from MSI installation, fallback to using executablePath for iconLocation
if (-Not $iconLocation) {
$iconLocation = $executablePath
}
}
} else {
# Not an MSI file, use executablePath for iconLocation
$iconLocation = $executablePath
}
VM-Install-Shortcut -toolName $toolName -category $category -executablePath $executablePath -consoleApp $consoleApp -arguments $arguments -iconLocation $iconLocation
Install-BinFile -Name $toolName -Path $executablePath
} catch {
VM-Write-Log-Exception $_
}
}
function VM-Uninstall-With-Uninstaller {
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $toolName,
[Parameter(Mandatory=$true, Position=1)]
[string] $category,
[Parameter(Mandatory=$true, Position=2)]
[ValidateSet("EXE", "MSI")]
[string] $fileType,
[Parameter(Mandatory=$true, Position=3)]
# Some general silent args:
# $silentArgs = '/qn /norestart' # MSI
# $silentArgs = '/S' # NSIS
# $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' # Inno Setup
# $silentArgs = '/s' # InstallShield
# $silentArgs = '/s /v"/qn"' # InstallShield with MSI
# $silentArgs = '/s' # Wise InstallMaster
# $silentArgs = '-s' # Squirrel
# $silentArgs = '-q' # Install4j
# $silentArgs = '-s -u' # Ghost
[string] $silentArgs,
[Parameter(Mandatory=$false)]
[array] $validExitCodes= @(0, 3010, 1605, 1614, 1641)
)
# Remove tool shortcut
VM-Remove-Tool-Shortcut $toolName $category
# Attempt to find and execute the uninstaller, may need to use wildcards
# See: https://docs.chocolatey.org/en-us/create/functions/get-uninstallregistrykey
[array]$key = Get-UninstallRegistryKey -SoftwareName $toolName
if ($key.Count -eq 1) {
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
fileType = $fileType
silentArgs = $silentArgs
# May need to remove arguments if present, but leaving for future TODO
file = $key[0].UninstallString
validExitCodes = $validExitCodes
}
if ($fileType -eq 'MSI') {
$packageArgs['silentArgs'] = "$($key[0].PSChildName) $silentArgs"
$packageArgs['file'] = ''
}
Uninstall-ChocolateyPackage @packageArgs
} elseif ($key.Count -eq 0) {
VM-Write-Log "WARN" "${Env:ChocolateyPackageName} has already been uninstalled by other means."
} elseif ($key.Count -gt 1) {
VM-Write-Log "WARN" "$($key.Count) matches found!"
VM-Write-Log "WARN" "To prevent accidental data loss, no targeted uninstallation will occur."
VM-Write-Log "WARN" "The following installation values were found:"
$key | ForEach-Object {VM-Write-Log "WARN" " - $($_.DisplayName)"}
VM-Write-Log "WARN" "Now allowing Chocolatey's auto uninstaller a chance to run."
}
# Remove tool files
$toolDir = Join-Path ${Env:RAW_TOOLS_DIR} $toolName
Remove-Item $toolDir -Recurse -Force -ea 0 | Out-Null
}
function VM-Write-Log-Exception {
Param
(
[Parameter(Mandatory=$true)]
[System.Management.Automation.ErrorRecord] $error_record
)
$msg = $error_record.Exception.Message
$position_msg = $error_record.InvocationInfo.PositionMessage
VM-Write-Log "ERROR" "$msg`r`n$position_msg"
throw $error_record
}
function VM-Add-To-Right-Click-Menu {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String] $menuKey, # name of registry key
[Parameter(Mandatory=$true, Position=1)]
[string] $menuLabel, # value displayed in right-click menu
[Parameter(Mandatory=$true, Position=2)]
[string] $command,
[Parameter(Mandatory=$false, Position=3)]
[string] $menuIcon,
[Parameter(Mandatory=$false)]
[ValidateSet("file", "directory")]
[string] $type="file",
[Parameter(Mandatory=$false)]
[string] $extension,
[Parameter(Mandatory=$false)]
[switch] $background
)
try {
if ($extension) {
$key = "SystemFileAssociations\$extension"
} else {
# Determine if file or directory should show item in right-click menu
if ($type -eq "file") {
$key = "*"
} else {
$key = "Directory"
if ($background) {
$key += "\Background"
}
}
}
$key_path = "HKCR:\$key\shell\$menuKey"
# Check and map "HKCR" to correct drive
if (-NOT (Test-Path -path 'HKCR:')) {
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null
}
# Add right-click menu display name
if (-NOT (Test-Path -LiteralPath $key_path)) {
New-Item -Path $key_path -Force | Out-Null
}
Set-ItemProperty -LiteralPath $key_path -Name '(Default)' -Value "$menuLabel" -Type String
if ($menuIcon) {
Set-ItemProperty -LiteralPath $key_path -Name 'Icon' -Value "$menuIcon" -Type String
}
# Add command to run when executed from right-click menu
if(-NOT (Test-Path -LiteralPath "$key_path\command")) {
New-Item -Path "$key_path\command" | Out-Null
}
Set-ItemProperty -LiteralPath "$key_path\command" -Name '(Default)' -Value $command -Type String
} catch {
VM-Write-Log "ERROR" "Failed to add $menuKey to right-click menu"
}
}
function VM-Remove-From-Right-Click-Menu {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String] $menuKey, # name of registry key
[Parameter(Mandatory=$false)]
[ValidateSet("file", "directory")]
[string] $type="file",
[Parameter(Mandatory=$false)]
[string] $extension,
[Parameter(Mandatory=$false)]
[switch] $background
)
try {
if ($extension) {
$key = "SystemFileAssociations\$extension"
} else {
# Determine if file or directory should show item in right-click menu
if ($type -eq "file") {
$key = "*"
} else {
$key = "Directory"
if ($background) {
$key += "\Background"
}
}
}
$key_path = "HKCR:\$key\shell\$menuKey"
# Check and map "HKCR" to correct drive
if (-NOT (Test-Path -path 'HKCR:')) {
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null
}
# Remove right-click menu settings from registry
if (Test-Path -LiteralPath $key_path) {
Remove-Item -LiteralPath $key_path -Recurse
}
} catch {
VM-Write-Log "ERROR" "Failed to remove $menuKey from right-click menu"
}
}
# Add associations to the file extension key
function VM-Set-Open-With-Association {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $executablePath,
[Parameter(Mandatory = $true)]
[string] $extension
)
try {
# Extract the executable name without path or extension
$exeName = [System.IO.Path]::GetFileNameWithoutExtension($executablePath)
ForEach ($hive in @("HKCU:", "HKLM:")) {
# Create the 'command' key and its default value
$commandKey = "${hive}\Software\Classes\${exeName}_auto_file\shell\open\command"
New-Item -Path $commandKey -Force
New-ItemProperty -Path $commandKey -Name '(Default)' -Value "`"$executablePath`" `"%1`" %*"
# Create/update the file extension key