-
Notifications
You must be signed in to change notification settings - Fork 2
/
hyper_v-toolbox.ps1
2293 lines (1857 loc) · 77.6 KB
/
hyper_v-toolbox.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
<#
.SYNOPSIS
Hyper-V Toolbox is an interactive PowerShell script inspired by Docker and Vagrant, designed for efficient virtual machine management.
.DESCRIPTION
This project is dedicated to providing users with an efficient and user-friendly tool for virtual machine management. With a focus on streamlining the virtual machine management process, this tool offers a range of features designed to enhance productivity and simplify operations.
.PARAMETER
-help: Displays the help menu for Hyper-V Toolbox.
.INPUTS
None. Interactive inputs via prompts.
.OUTPUTS
Text-based outputs to the console detailing the VM management process.
.REQUIREMENTS
PowerShell 5.0 or later.
Hyper-V Module.
.LICENSE
GNU Affero General Public License v3.0. Please see the [LICENSE] file on the GitHub repository (https://github.com/franckferman/Hyper-V_Toolbox/blob/main/LICENSE) for the full license details.
.CREDITS
Inspired by Docker (https://www.docker.com/) and Vagrant (https://www.vagrantup.com/).
.EXAMPLE
PS > Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process; .\hyper-v_toolbox.ps1
.NOTES
Author: Franck Ferman
Version: 1.0.0
.LINK
https://github.com/franckferman/Hyper-V_Toolbox
#>
param (
[Switch]$help
)
[String]$Script:scriptVersion = "1.0.0"
# Declaration of Global variables containing download links to JSON files allowing access to downloadable resources (images and virtual hard drives).
# Recover files containing links to resources from GitHub.
[System.Uri]$Script:Blank_Windows_JSON_LinksFile = 'https://raw.githubusercontent.com/franckferman/Hyper-V_Toolbox/main/assets/links/blank_windows.json'
[System.Uri]$Script:Blank_Linux_JSON_LinksFile = 'https://raw.githubusercontent.com/franckferman/Hyper-V_Toolbox/main/assets/links/blank_linux.json'
# [System.Uri]$Script:Preconfigured_Windows_JSON_Links_File = 'https://raw.githubusercontent.com/franckferman/Hyper-V_Toolbox/main/assets/links/preconfigured_windows.json'
# [System.Uri]$Script:Preconfigured_Linux_JSON_Links_File = 'https://raw.githubusercontent.com/franckferman/Hyper-V_Toolbox/main/assets/links/preconfigured_linux.json'
# Recover files containing links to resources from Google Drive.
# [System.Uri]$Script:Blank_Windows_JSON_LinksFile = 'https://drive.google.com/file/d/id/view?usp=sharing'
# [System.Uri]$Script:Blank_Linux_JSON_LinksFile = 'https://drive.google.com/file/d/id/view?usp=sharing'
# [System.Uri]$Script:Preconfigured_Windows_JSON_Links_File = 'https://drive.google.com/file/d/id/view?usp=sharing'
# [System.Uri]$Script:Preconfigured_Linux_JSON_Links_File = 'https://drive.google.com/file/d/id/view?usp=sharing'
# Recover files containing links to resources from Proton Drive.
# Examples to be defined.
# Recover files containing links to resources from a local resource or network share.
# [String]$Script:Blank_Windows_JSON_LinksFile = '\\COMPUTER\SHARE'
# [String]$Script:Blank_Linux_JSON_LinksFile = '\\COMPUTER\SHARE'
# [System.Uri]$Script:Preconfigured_Windows_JSON_Links_File = ''\\COMPUTER\SHARE'
# [System.Uri]$Script:Preconfigured_Linux_JSON_Links_File = ''\\COMPUTER\SHARE'
# Declaration of banner groups.
[Array]$Script:Window_Banners = @("Window_PS_Terminal", "Window_PS_Terminal_Old_Computer", "Teddy_Screen")
[Array]$Script:Windows_Banners = @("Windows_logo", "Windows_on_laptop")
[Array]$Script:Linux_Banners = @("Linux_Penguin", "Linux_Devil", "Talking_Linux_Penguin", "Cowsay")
[Array]$Script:Space_Banners = @("Rocket_launch", "Space_odyssey", "Galaxy")
[Array]$Script:Misc_Banners = @("Monkey", "HPV-TBX_text")
function Display-Help {
<#
.SYNOPSIS
Displays the help menu for Hyper-V Toolbox.
.DESCRIPTION
This function generates and presents the help menu for Hyper-V Toolbox, outlining how to use the script and its potential options.
#>
Write-Host "Hyper-V Toolbox Help Menu"
Write-Host "--------------------------"
Write-Host "To run Hyper-V Toolbox in interactive mode, simply execute:"
Write-Host "PS > .\hyper-v_toolbox.ps1"
Write-Host ""
Write-Host "Options:"
Write-Host "-h, --help Display this help menu."
Write-Host ""
Write-Host "Once inside the interactive mode, follow on-screen prompts to manage your virtual machines."
}
function Test-AdminRights {
[CmdletBinding()]
[OutputType([Bool])]
param()
<#
.SYNOPSIS
Tests if the current user has administrator rights.
.DESCRIPTION
This function will determine if the current user is part of the Administrator role. It utilizes the .NET classes for Windows Security and Principal Windows Built-in Roles to make this determination.
.EXAMPLE
if (Test-AdminRights) {
Write-Host "You are running as an administrator."
} else {
Write-Host "You are not running as an administrator."
}
#>
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
return $principal.IsInRole($adminRole)
}
function Test-Prerequisites {
<#
.SYNOPSIS
Checks if the necessary prerequisites are met.
.DESCRIPTION
This function verifies if the Hyper-V feature is enabled and if the PowerShell version is at least 5.
.EXAMPLE
if (Test-Prerequisites) {
Write-Host "All prerequisites are met."
} else {
Write-Host "Some prerequisites are missing."
}
#>
$hyperVEnabled = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online |
Where-Object {$_.State -eq 'Enabled'}
if (-not $hyperVEnabled) {
Write-Warning "Hyper-V feature is not enabled."
return $false
}
Import-Module Hyper-V
$psVersion = $PSVersionTable.PSVersion.Major
if ($psVersion -lt 5) {
Write-Warning "PowerShell version is below 5. Current version: $psVersion"
return $false
}
return $True
}
function Get-WANStatus {
<#
.SYNOPSIS
Tests the WAN connection by trying to reach one of the provided URLs.
.DESCRIPTION
This function randomly selects one of the provided URLs (or default URLs if none are provided) and attempts to reach it.
If successful, it returns "Online". Otherwise, it returns "Offline" or provides an error message.
.PARAMETER urls
An array of URLs to be tested. If none are provided, default URLs are used.
.EXAMPLE
Get-WANStatus -urls 'https://httpbin.org/get'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[System.Uri[]]$urls = @('https://httpbin.org/get', 'https://httpstat.us/200')
)
[String]$selectedUrl = Get-Random -InputObject $urls -Count 1
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
try {
$ProgressPreference = 'SilentlyContinue'
$response = Invoke-WebRequest -Uri $selectedUrl -WebSession $webSession -Headers @{
'User-Agent' = 'Hyper-V_Toolbox/1.0.0'
} -UseBasicParsing -TimeoutSec 5
if ([Byte]$response.StatusCode -eq 200) {
return "Online"
} else {
return "Offline - Received status code $($response.StatusCode)"
}
} catch {
return "Offline - Error: $($_.Exception.Message)"
}
}
function Get-Update {
<#
.SYNOPSIS
Checks if there's an update available for the script from the provided repository.
.DESCRIPTION
This function fetches the content of the script from the specified repository URL, extracts the version, and compares it with the current script's version.
.PARAMETER repositoryUrl
The URL to the raw content of the script in the repository. Default is the provided GitHub repository.
.EXAMPLE
if (Get-Update) {
Write-Host "An update is available."
} else {
Write-Host "You have the latest version."
}
#>
[CmdletBinding()]
[OutputType([Bool])]
param (
[Parameter(Mandatory=$false)]
[System.Uri]$repositoryUrl = 'https://raw.githubusercontent.com/franckferman/Hyper-V_Toolbox/main/hyper-v_toolbox.ps1'
)
try {
$ProgressPreference = 'SilentlyContinue'
$Content = (Invoke-WebRequest -Uri $repositoryUrl -UseBasicParsing -TimeoutSec 5).Content
$VersionMatch = [regex]::Match($Content, 'Version:\s*(\d+\.\d+\.\d+)')
if (-not $VersionMatch.Success) {
throw "Failed to extract the script version from the repository."
}
[System.Version]$CurrentVersion = New-Object System.Version $scriptVersion
[System.Version]$RepositoryVersion = New-Object System.Version $VersionMatch.Groups[1].Value
return $CurrentVersion -lt $RepositoryVersion
} catch [System.Net.WebException] {
Write-Warning "Failed to connect to the repository. Check your internet connection and try again."
} catch {
Write-Warning "An unexpected error occurred during the script update check: $($_.Exception.Message)"
}
return $false
}
function PauseForUser {
<#
.SYNOPSIS
Pauses script execution until the user presses Enter.
.DESCRIPTION
Displays a message prompting the user to press Enter to continue.
#>
Read-Host 'Press enter to continue...'
}
function Select-main_Menu {
<#
.SYNOPSIS
Main menu loop for user interaction.
.DESCRIPTION
This function loops continuously, displaying the main menu and processing user input.
#>
while ($True) {
Show-main_Menu
Write-Host ''
$choice = Read-Host 'Enter your choice'
Switch ($choice) {
'1' { Select-BlankVM-Menu }
'2' { Show-UnderDevelopmentMessage }
'3' { Show-UnderDevelopmentMessage }
'4' { Show-UnderDevelopmentMessage }
'5' { Show-UnderDevelopmentMessage }
'6' { LocalResourceManagement-Menu }
'h' { Write-Host (Display_interactive_help) ; Write-Host '' ; PauseForUser }
'q' { Write-Host '' ; ScriptExit -ExitCode 0 }
default { Show-InvalidInput }
}
}
}
function Show-Banner {
<#
.SYNOPSIS
Displays an artistic banner in the console.
.DESCRIPTION
The Show-Banner function allows you to display different types of artistic banners in the console.
.PARAMETER BannerType
Specifies the type of banner to display.
If not specified, a random banner will be shown, except Buddha, which is used for the main menu only.
.EXAMPLE
Show-Banner -BannerType "Buddha"
This command displays the "Buddha" banner.
#>
param (
[Parameter(Mandatory = $false)]
[ValidateSet("Buddha", "Window_PS_Terminal", "Window_PS_Terminal_Old_Computer", "Teddy_Screen", "Monkey", "Linux_Penguin", "Linux_Devil", "Talking_Linux_Penguin", "Cowsay", "Windows_logo", "Windows_on_laptop", "Rocket_launch", "Space_odyssey", "Galaxy", "HPV-TBX_text", "Window_Banners", "Windows_Banners", "Linux_Banners", "Space_Banners", "Misc_Banners")]
[String]$BannerType = (Get-Random -InputObject @("Window_PS_Terminal", "Window_PS_Terminal_Old_Computer", "Teddy_Screen", "Monkey", "Linux_Penguin", "Linux_Devil", "Talking_Linux_Penguin", "Cowsay", "Windows_logo", "Windows_on_laptop", "Rocket_launch", "Space_odyssey", "Galaxy", "HPV-TBX_text"))
)
Switch ($BannerType) {
"Window_Banners" { $BannerType = Get-Random -InputObject $Window_Banners ; Show-Banner $BannerType }
"Windows_Banners" { $BannerType = Get-Random -InputObject $Windows_Banners ; Show-Banner $Windows_Banners }
"Linux_Banners" { $BannerType = Get-Random -InputObject $Linux_Banners ; Show-Banner $Linux_Banners }
"Space_Banners" { $BannerType = Get-Random -InputObject $Space_Banners ; Show-Banner $Space_Banners }
"Misc_Banners" { $BannerType = Get-Random -InputObject $Misc_Banners ; Show-Banner $Misc_Banners }
"Buddha" {
@"
_
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/'---'\____
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||_ \
| | \\\ - /'| | |
| \_| '\'---'// |_/ |
\ .-\__ '-. -'__/-. /
___'. .' /--.--\ '. .'___
."" '< '.___\_<|>_/___.' _> \"".
| | : '- \'. ;'. _/; .'/ / .' ; |
\ \ '-. \_\_'. _.'_/_/ -' _.' /
==========='-.'___'-.__\ \___ /__.-'_.'_.-'================
'=--=-'
_____ _ _
/\ /\_ _ _ __ ___ _ __ /\ /\ /__ \___ ___ | | |__ _____ __
/ /_/ / | | | '_ \ / _ \ '__|___\ \ / / / /\/ _ \ / _ \| | '_ \ / _ \ \/ /
/ __ /| |_| | |_) | __/ | |_____\ V / / / | (_) | (_) | | |_) | (_) > <
\/ /_/ \__, | .__/ \___|_| \_/ \/ \___/ \___/|_|_.__/ \___/_/\_\
|___/|_|
"@
}
"Window_PS_Terminal" {
@"
_______________________________________________________________________
|[>] Hyper-V Toolbox [-]|[]|[x]"|
|"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""|"|
|PS C:\WINDOWS\system32> Set-Location -Path C:\Users\$env:USERNAME | |
|PS C:\Users\$env:USERNAME> .\hyper-v_toolbox.ps1 | |
| |_|
|_____________________________________________________________________|/|
"@
}
"Window_PS_Terminal_Old_Computer" {
@"
.---------.
|.-------.|
||PS C:\>||
|| ||
|"-------'|
.-^---------^-.
| ---~[HPV |
| Toolbox]---~|
"-------------'
"@
}
"Teddy_Screen" {
@"
,---. ,---.
/ /"'.\.--"""--./,'"\ \
\ \ _ _ / /
'./ / __ __ \ \,'
/ /_O)_(_O\ \
| .-' ___ '-. |
.--| \_/ |--.
,' \ \ | / / '.
/ '. '--^--' ,' \
.-"""""-. '--.___.--' .-"""""-.
.-----------/ \------------------/ \--------------.
| .---------\ /----------------- \ /------------. |
| | '-'--'--' '--'--'-' | |
| | | |
| | __7__ %%%,%%%%%%% | |
| | \_._/ ,'%% \\-*%%%%%%% | |
| | ( ^ ) ;%%%%%*% _%%%% | |
| | '='|\. ,%%% \(_.*%%%%. | |
| | / | % *%%, ,%%%%*( ' | |
| | (/ | %^ ,*%%% )\|,%%*%,_ | |
| | |__, | *% \/ #).-*%%* | |
| | | | _.) ,/ *%, | |
| | | | _________/)#(_____________ | |
| | /___| |__________________________| | |
| | === [Hyper-V Toolbox] | |
| |_____________________________________________________________| |
|_________________________________________________________________|
)__________|__|__________(
| || |
|____________||____________|
),-----.( ),-----.(
,' ==. \ / .== '.
/ ) ( \
'===========' '==========='
"@
}
"Monkey" {
@"
.="=.
_/.-.-.\_ _
( ( o o ) ) ))
.-------. |/ " \| //
| HPV | \'---'/ //
_| TBX |_ /'"""'\\ ((
=(_|_______|_)= / /_,_\ \\ \\
|:::::::::| \_\\_'__/ \ ))
|:::::::[]| /' /'~\ |//
|o=======.| / / \ /
'"""""""""' ,--',--'\/\ /
'-- "--' '--'
"@
}
"Linux_Penguin" {
@"
.---.
/ \
\.@-@./
/'\_/'\
// _ \\
| \ )|_
/'\_'> <_/ \
\__/'---'\__/
"@
}
"Linux_Devil" {
@"
, ,
/( )'
\ \___ / |
/- _ '-/ '
(/\/ \ \ /\
/ / | ' \
O O ) / |
'-^--''< '
(_.) _ ) /
'.___/' /
'-----' /
<----. __ / __ \
<----|====O)))==) \) /====
<----' '--' '.__,' \
| |
\ /
______( (_ / \______
,' ,-----' | \
'--{__________) \/
"@
}
"Talking_Linux_Penguin" {
@"
_nnnn_
dGGGGMMb ,""""""""""""""""".
@p~qp~~qMb | Hyper-V Toolbox |
M|@||@) M| _;.................'
@,----.JM| -'
JS^\__/ qKL
dZP qKRb
dZP qKKb
fZP SMMb
HZM MMMM
FqM MMMM
__| ". |\dS"qML
| '. | '' \Zq
_) \.___.,| .'
\____ )MMMMMM| .'
'-' '--'
"@
}
"Cowsay" {
@"
__________________
( Hyper-V Toolbox )
------------------
o ^__^
o (oo)\_______
(__)\ )\/\
||----w |
|| ||
"@
}
"Windows_logo" {
@"
.----------------.
| _ |
| _.-'|'-._ |
| .__.| | | |
| |_.-'|'-._| |
| '--'| | | |
| '--'|_.-'-'-._| |
| '--' |
'----------------'
"@
}
"Windows_on_laptop" {
@"
._________________.
|.---------------.|
|| -._ .-. ||
|| -._| | | ||
|| -._|"|"| ||
|| -._|.-.| ||
||_______________||
/.-.-.-.-.-.-.-.-.\
/.-.-.-.-.-.-.-.-.-.\
/.-.-.-.-.-.-.-.-.-.-.\
/______/__________\___o_\
\_______________________/
"@
}
"Rocket_launch" {
@"
* * * *
* *
* * ___
* * | | |
* _________## * / \ | |
@\\\\\\\\\## * | |--o|===|-|
* @@@\\\\\\\\##\ \|/|/ |---| | |
@@ @@\\\\\\\\\\\ \|\\|//|/ * / \ | |
* @@@@@@@\\\\\\\\\\\ \|\|/|/ | H-T | | |
@@@@@@@@@----------| \\|// | P-B |=| |
__ @@ @@@ @@__________| \|/ | V-X | | |
____|_@|_ @@@@@@@@@__________| \|/ |_______| |_|
=|__ _____ |= @@@@ .@@@__________| | |@| |@| | |
____0_____0__\|/__@@@@__@@@__________|_\|/__|___\|/__\|/___________|_|_
"@
}
"Space_odyssey" {
@"
_.--"""""--._
,-' '-.
_ ,' --- - ---- --- '.
,'|'. ,' ________________'.
O'.+,'O / /____(_______)___\ \
_......_ ,=. __________; _____ ____ _____ _____ :
,' ,--.-',,;,:,;;;;;;;///////////| ----- ---- ----- ----- |
( ( ==)=========================| ,---. ,---. ,. |
'._ '--'-,''''''"""""""\\\\\\\\\\\: /'. ,'\ /_ \ /\/\ ;
'''''' \ : Y : :-'-. : : ): /
'. \ | / \=====/ \/\/'
'. '-'-' '---' ;'
'-._ _,-'
'--.....--' ,--.
().0()
''-'
"@
}
"Galaxy" {
@"
. . . . . . . . .
. . . _......____._ . .
. . . ..--'"" . """"""---... .
_...--"" ................ '-. .
.-' ...:'::::;:::%:.::::::_;;:... '-.
.-' ..::::''''' _...---'"""":::+;_::. '. .
. .' . ..::::' _.-"" :::)::. '.
. ..;:::' _.-' . f::':: o _
/ .:::%' . .-" .-. ::;;:. /" "x
. .' ""::.::' .-" _.--'"""-. ( ) ::.:: |_.-' |
.' ::;:' .' .-" .d@@b. \ . . '-' ::%:: \_ _/ .
.' :,::' / . _' 8@@@@8 j .-' ::::: " o
| . :.%:' . j (_) '@@@P' .' .-" ::.:: . f
| :::: ( -..____...-' .-" .::::' /
. | ':':: '. ..--' . .::':: . /
j '::::: '-._____...---"" .::%:::' .' .
\ ::.:%.. . . ...:,::::' .'
. \ ':::':.. ....::::.::::' .-' .
\ . '':::%::'::.......:::::%::.::::'' .-'
. '. . ''::::::%::::.::;;:::::''' _.-' .
. '-.. . . ''''''''' . _.-' . .
. ""--...____ . ______......--' . . .
. . . """""""" . . . . .
"@
}
"HPV-TBX_text" {
@"
_ ___ _ _____ ___ _
| |_| | |_) \ \ / | | | |_) \ \_/
|_| | |_| \_\/ |_| |_|_) /_/ \
"@
}
}
}
function Display_interactive_help {
<#
.SYNOPSIS
Displays the interactive help menu for the Hyper-V Toolbox.
.DESCRIPTION
The function presents an ASCII-styled help menu for the Hyper-V Toolbox, providing a brief description and visual representation of the tool.
#>
[console]::Clear()
@"
_______________________
_______________________------------------- '\
/:--__ |
||< > | ___________________________/
| \__/_________________------------------- |
| |
| HYPER-V Toolbox |
| Interactive Help Menu |
| |
| "Hyper-V Toolbox is an interactive PowerShell script |
| designed for efficient virtual machine management." |
| |
| ____________________|_
| ___________________------------------------- '\
|/'--_ |
||[ ]|| ___________________/
\===/___________________--------------------------
"@
}
function ScriptExit {
<#
.SYNOPSIS
Terminates the script execution with a given exit code.
.DESCRIPTION
This function provides a unified exit point for the script, logging the exit reason, and using the provided exit code.
An exit code of 0 usually indicates success, while any other number indicates an error.
.PARAMETER ExitCode
The exit code to terminate the script with. Default is 0, indicating a normal exit.
.PARAMETER ExitMessage
Optional custom message to display before exiting.
.EXAMPLE
ScriptExit -ExitCode 1 -ExitMessage "An unexpected error occurred."
.EXAMPLE
ScriptExit # This will exit with a code of 0 (indicating success).
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[int]$ExitCode = 0,
[Parameter(Position = 1)]
[String]$ExitMessage = "Exiting script with exit code $ExitCode"
)
if ($ExitCode -eq 0) {
Write-Host $ExitMessage -ForegroundColor Green
} else {
Write-Warning $ExitMessage
}
exit $ExitCode
}
function Show-UnderDevelopmentMessage {
<#
.SYNOPSIS
Displays a message indicating that a feature is under development.
.DESCRIPTION
Used for menu options that are placeholders for future functionality.
#>
Write-Host ''
Write-Warning 'Feature under development.'
PauseForUser
}
function Show-InvalidInput {
<#
.SYNOPSIS
Notifies the user of an invalid input.
.DESCRIPTION
This function provides a visual cue and pauses the script to inform the user about an invalid input.
It will display a warning message and await user confirmation before proceeding.
.EXAMPLE
Show-InvalidInput
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline = $True)]
[String]$CustomMessage = 'Invalid entry detected.'
)
Write-Host "`n" -NoNewline
Write-Warning $CustomMessage
Read-Host 'Press enter to continue...'
}
function Select-BlankVM-Menu {
<#
.SYNOPSIS
BlankVM OS selection menu loop for user interaction.
.DESCRIPTION
This function loops continuously, displaying the OS selection menu and processing user input.
#>
while ($True) {
Show-BlankVM-Menu
Write-Host ''
$choice = Read-Host 'Enter your choice'
Switch ($choice) {
'1' { BlankVM_exec -OperatingSystem 'Windows' }
'2' { BlankVM_exec -OperatingSystem 'Linux' }
'b' { Select-main_Menu }
'q' { Write-Host '' ; ScriptExit -ExitCode 0 }
default { Show-InvalidInput }
}
}
}
function Show-BlankVM-Menu {
<#
.SYNOPSIS
Displays the OS selection menu for the BlankVM Menu of Hyper-V Toolbox.
.DESCRIPTION
This function shows the user a list of operating systems they can choose from.
#>
$banner = Show-Banner -BannerType "Window_Banners"
$menuItems = @(
"1 - Windows",
"2 - Linux",
"",
"b - Back",
"q - Quit the program"
)
[console]::Clear()
$banner
Write-Host "`nHyper-V Toolbox - Blank VM Menu - OS selection"
Write-Host ('-' * 30)
$menuItems | ForEach-Object { Write-Host $_ }
}
function BlankVM_exec {
<#
.SYNOPSIS
Creates a new virtual machine based on the provided operating system.
.DESCRIPTION
The BlankVM_exec function processes the creation of a new virtual machine using the specified operating system. It defines paths and URLs based on the selected operating system, checks the VM links, and sets up and creates the new VM. This function serves as a wrapper and orchestrator for the VM creation process.
.PARAMETER OperatingSystem
Specifies the operating system type for the virtual machine. Acceptable values are "Windows" and "Linux". This parameter is mandatory.
.EXAMPLE
BlankVM_exec -OperatingSystem 'Windows'
This command creates a new virtual machine with a Windows operating system.
.EXAMPLE
BlankVM_exec -OperatingSystem 'Linux'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[ValidateSet('Windows', 'Linux')]
[String]$OperatingSystem
)
DefinePathsAndURLs -OperatingSystem $OperatingSystem -Type Blank
ProcessVMLinks
SetupAndCreateVM -OperatingSystem $OperatingSystem -Type Blank
}
function DefinePathsAndURLs {
<#
.SYNOPSIS
Defines the paths and URLs based on the provided operating system and VM type.
.DESCRIPTION
The DefinePathsAndURLs function determines the appropriate paths and URLs for assets and link files based on the provided operating system type (Windows or Linux) and VM type (Blank or Preconfigured). The function uses a nested hashtable mapping for a cleaner lookup of paths and URLs. It sets the paths and URLs as Global variables for subsequent use in other functions.
.PARAMETER OperatingSystem
Specifies the operating system type for which the paths and URLs are to be defined. Acceptable values are "Windows" and "Linux". This parameter is mandatory.
.PARAMETER Type
Specifies the type of VM for which the paths and URLs are to be defined. Acceptable values are "Blank" and "Preconfigured". This parameter is mandatory.
.EXAMPLE
DefinePathsAndURLs -OperatingSystem 'Windows' -Type 'Blank'
This command determines the paths and URLs for assets and link files related to the Windows operating system with a Blank VM type.
.EXAMPLE
DefinePathsAndURLs -OperatingSystem 'Linux' -Type 'Preconfigured'
#>
param (
[Parameter(Mandatory = $true)]
[ValidateSet('Windows', 'Linux')]
[String]$OperatingSystem,
[Parameter(Mandatory = $true)]
[ValidateSet('Blank', 'Preconfigured')]
[String]$Type
)
$osMap = @{
'Windows' = @{
'Blank' = @{
'JSONPath' = '.\assets\links\blank_windows.json';
'URL' = $Blank_Windows_JSON_LinksFile;
}
'Preconfigured' = @{
'JSONPath' = '.\assets\links\preconfigured_windows.json';
'URL' = $Preconfigured_Windows_JSON_LinksFile;
}
}
'Linux' = @{
'Blank' = @{
'JSONPath' = '.\assets\links\blank_linux.json';
'URL' = $Blank_Linux_JSON_LinksFile;
}
'Preconfigured' = @{
'JSONPath' = '.\assets\links\preconfigured_linux.json';
'URL' = $Preconfigured_Linux_JSON_LinksFile;
}
}
}
$Script:JSONFilePath = $osMap[$OperatingSystem][$Type]['JSONPath']
$Script:JSONFileURL = $osMap[$OperatingSystem][$Type]['URL']
}
function Ensure-Directory {
<#
.SYNOPSIS
Ensures that a directory exists at the specified path.
.DESCRIPTION
The Ensure-Directory function checks if a directory exists at the provided path. If the directory doesn't exist, it attempts to create it. If there's an error during the creation process, it raises an error and exits the script.
.PARAMETER Path
Specifies the path of the directory to check or create. This parameter is mandatory.
.EXAMPLE
Ensure-Directory -Path ".\assets\links"
This command checks if the ".\assets\links" directory exists. If not, it creates the directory.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]$Path
)
if (-not (Test-Path $Path -PathType Container)) {
try {
New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop | Out-Null
}
catch {
Write-Error "Failed to create directory '$Path': $_"
ScriptExit -ExitCode 1
}
}
}
function Get-GDriveFileID {
<#
.SYNOPSIS
Transforms a Google Drive shared link into a direct download link.
.DESCRIPTION
The Get-GDriveFileID function converts a Google Drive shared link into a direct download link format. If the input link is already in the correct format or is not a Google Drive link, the function might return the input link or $null.
.PARAMETER DriveFileSource
Specifies the Google Drive shared link that needs to be transformed. This parameter is mandatory.
.EXAMPLE
Get-GDriveFileID -DriveFileSource "https://drive.google.com/file/d/FILE_ID/view?usp=sharing"
This command transforms the provided Google Drive shared link into a direct download link.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]$DriveFileSource
)
if ($DriveFileSource.Contains('download&id')) {
# Return the link as it already seems to be in the desired format.
return $DriveFileSource
} elseif ($DriveFileSource -match "drive\.google\.com/file/d/([^/]+)/") {
$GFileID = $matches[1]
[String]$GDriveUrl = "https://drive.google.com/uc?export=download&id=$GFileID"
return $GDriveUrl
} else {
# Return $null if the link is not in the expected Google Drive format.
return $null
}
}
function Ensure-JSONDirectory {
<#
.SYNOPSIS
Ensures the presence of a JSON file, and if not found, initiates a download.
.DESCRIPTION
The Ensure-JSONDirectory function checks for the existence of a specified JSON file at the given destination path. If the file doesn't exist, the function attempts to download it from the specified source.
.PARAMETER JSONFilePathDestination
Specifies the path where the JSON file is expected to be located or where it should be downloaded.
.PARAMETER JSONFileDownloadSource
Specifies the source URL from where the JSON file should be downloaded if it's not found at the destination.
.EXAMPLE
Ensure-JSONDirectory -JSONFilePathDestination "\assets\links\blank_windows.json" -JSONFileDownloadSource "https://example.com/links.json"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]$JSONFilePathDestination,
[Parameter(Mandatory = $true)]
[String]$JSONFileDownloadSource
)
if (-not (Test-Path $JSONFilePathDestination)) {
Write-Host "`nAttempting to download the JSON configuration file containing image links."
try {
Invoke-WebRequest -Uri $JSONFileDownloadSource -OutFile $JSONFilePathDestination -TimeoutSec 5 -UseBasicParsing
Write-Host "JSON file successfully downloaded.`n"
PauseForUser
} catch {
Write-Error "Error downloading the JSON file: $_"
ScriptExit -ExitCode 1
}
}
}
function Read-FromJSON {
<#
.SYNOPSIS
Reads the contents of a JSON file and returns it as a PowerShell object.
.DESCRIPTION
The Read-FromJSON function takes the path to a JSON file as its input. It checks if the file exists and then reads its content, converting it to a PowerShell object before returning it. If the file is not found, or another error occurs, the function provides an error message and exits the script.
.PARAMETER JSONFilePathDestination
Specifies the path to the JSON file that needs to be read.
.EXAMPLE
$myData = Read-FromJSON -JSONFilePathDestination ".\assets\links\blank_windows.json"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]$JSONFilePathDestination
)
if (-not (Test-Path $JSONFilePathDestination)) {
Write-Warning "JSON configuration file not found at '$JSONFilePathDestination'."
ScriptExit -ExitCode 1
}