-
Notifications
You must be signed in to change notification settings - Fork 1
/
Invoke-NerdFontInstaller.ps1
executable file
·1509 lines (1326 loc) · 67.3 KB
/
Invoke-NerdFontInstaller.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
#!/usr/bin/env pwsh
<#PSScriptInfo
.VERSION 1.3.6
.GUID a3238c59-8a0e-4c11-a334-f071772d1255
.AUTHOR Julian Pawlowski
.COPYRIGHT © 2024 Julian Pawlowski.
.TAGS fonts nerdfonts cascadia-code cascadia-code-nerd-font cascadia-code-powerline-font cascadia-mono cascadia-mono-nerd-font cascadia-mono-powerline-font powershell powershell-script Windows MacOS Linux PSEdition_Core PSEdition_Desktop
.LICENSEURI https://github.com/jpawlowski/nerd-fonts-installer-PS/blob/main/LICENSE.txt
.PROJECTURI https://github.com/jpawlowski/nerd-fonts-installer-PS
.ICONURI https://raw.githubusercontent.com/jpawlowski/nerd-fonts-installer-PS/main/images/nerd-fonts-logo.png
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Version 1.3.6 (2024-12-05)
- Fix mandatory parameter check for non-interactive sessions
#>
<#
.SYNOPSIS
Install Nerd Fonts on Windows, macOS, or Linux.
You may also run this script directly from the web using the following command:
```powershell
& ([scriptblock]::Create((iwr 'https://to.loredo.me/Install-NerdFont.ps1')))
```
Parameters may be passed at the end just like any other PowerShell script.
.DESCRIPTION
An interactive installer for Nerd Fonts and Cascadia Code on Windows, macOS, or Linux.
The script downloads the font archive from the GitHub release pages and extracts the font files to
the user's font directory, or the system font directory when using the AllUsers scope with
elevated permissions.
Besides installing the script locally, you may also run this script directly from the web
using the following command:
```powershell
& ([scriptblock]::Create((iwr 'https://to.loredo.me/Install-NerdFont.ps1')))
```
Or alternatively without the shortened URL:
```powershell
& ([scriptblock]::Create((iwr 'https://raw.githubusercontent.com/jpawlowski/nerd-fonts-installer-PS/main/Invoke-NerdFontInstaller.ps1')))
```
> **IMPORTANT**: A code signature cannot be verified when running the script directly from the web.
> SSL transport layer encryption is used to protect the script during download from GitHub and during
> redirection from the URL shortener.
Parameters may be passed just like any other PowerShell script. For example:
```powershell
& ([scriptblock]::Create((iwr 'https://to.loredo.me/Install-NerdFont.ps1'))) -Name cascadia-code, cascadia-mono
```
To get a list of available Nerd Fonts, use the following command:
```powershell
& ([scriptblock]::Create((iwr 'https://to.loredo.me/Install-NerdFont.ps1'))) -List All
```
.PARAMETER Help
Show help content for the script or a specific parameter.
The following values are supported:
- Name: Shows help for the dynamic Name parameter (which is not possible using regular Get-Help)
- Variant: Shows help for the Variant parameter.
- Type: Shows help for the Type parameter.
- All: Shows help for the All parameter.
- List: Shows help for the List parameter.
- Scope: Shows help for the Scope parameter.
- Force: Shows help for the Force parameter.
- Help: Shows help for the Help parameter.
- Version: Shows help for the Version parameter.
- Summary: Provides a summary of the help content. Note that the dynamic Name parameter is not included in the summary.
- Detailed: Provides detailed help, including parameter descriptions and examples. Note that the dynamic Name parameter is not included in the detailed help.
- Full: Provides full help, including detailed help, parameter descriptions, examples, and additional notes. Note that the dynamic Name parameter is not included in the full help.
- Examples: Shows only the examples section of the help.
.PARAMETER Name
The name of the Nerd Font to install.
Multiple font names can be specified as an array of strings.
If no font name is specified, the script provides an interactive menu to select the font to install
(unless the All parameter is used).
The menu is displayed only if the script is run in an interactive session.
If the script is run in a non-interactive environment, the Name parameter is mandatory and must be specified.
Possible font names are dynamically retrieved from the Nerd Font library on GitHub.
To see a list of available fonts, use the parameter '-List All'.
.PARAMETER Variant
Specify the font variant to install.
The default value is 'Variable'.
A variable font is a single font file that can contain multiple variations of a typeface while a static font
is a traditional font file with a single style.
For example, a variable font can contain multiple weights and styles in a single file.
Most Nerd Fonts are only available as static fonts. The only exception today is Microsoft's Cascadia Code
font where variable fonts are recommended to be used for all platforms.
Setting this parameter to 'Static' will search for a folder with the name 'static' in the font archive.
If that was found, files from that folder will be installed, otherwise, the script will install the font files
from the root of the archive (or the folder for the font type, if any is found).
.PARAMETER Type
Specify the order to search for font types. Only the first matching type will be installed.
The default order is TTF, OTF, WOFF2.
The script will search for folders with the specified type name in the font archive, and if found, install the fonts from that folder.
If no folder is found, the script will install the font files from the root of the archive.
The script will search for files with the specified type extension in any case.
.PARAMETER All
Install all available Nerd Fonts.
You will be prompted to confirm the installation for each font with the option to skip, cancel,
or install all without further confirmation.
.PARAMETER List
List available Nerd Fonts matching the specified pattern.
Use '*' or 'All' to list all available Nerd Fonts.
This parameter does not install any fonts.
.PARAMETER Scope
Defined the scope in which the Nerd Font should be installed.
The default value is CurrentUser.
The AllUsers scope requires elevated permissions.
The CurrentUser scope installs the font for the current user only.
.PARAMETER Force
Overwrite existing font files instead of skipping them.
.PARAMETER Version
Display the version of the script.
.EXAMPLE
Invoke-NerdFontInstaller -Name cascadia-code
Install the Cascadia Code Font Family from the Microsoft repository.
.EXAMPLE
Invoke-NerdFontInstaller -Name cascadia-mono
Install the Cascadia Mono Font Family from the Microsoft repository.
.EXAMPLE
Invoke-NerdFontInstaller -Name cascadia-code, cascadia-mono
Install the Cascadia Code and Cascadia Mono Font Families from the Microsoft repository.
.EXAMPLE
Invoke-NerdFontInstaller -All -WhatIf
Show what would happen if all fonts were installed.
.EXAMPLE
Invoke-NerdFontInstaller -List cascadia*
List all fonts with names starting with 'cascadia'.
.EXAMPLE
Invoke-NerdFontInstaller -Help Name
Get help for the dynamic Name parameter.
.EXAMPLE
Invoke-NerdFontInstaller -Help ?
Get explanation of the available help options.
.NOTES
This script must be run on your local machine, not in a container.
#>
[CmdletBinding(DefaultParameterSetName = 'ByName', SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $false, ParameterSetName = 'ByAll', HelpMessage = 'Which Font variant do you prefer?')]
[Parameter(Mandatory = $false, ParameterSetName = 'ByName', HelpMessage = 'Which Font variant do you prefer?')]
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
@('Variable', 'Static') | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
})]
[ValidateSet('Variable', 'Static')]
[string]$Variant = 'Variable',
[Parameter(Mandatory = $false, ParameterSetName = 'ByAll', HelpMessage = 'Specify the order to search for font types. Only the first matching type will be installed.')]
[Parameter(Mandatory = $false, ParameterSetName = 'ByName', HelpMessage = 'Specify the order to search for font types. Only the first matching type will be installed.')]
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
@('TTF', 'OTF', 'WOFF2') | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
})]
[ValidateSet('TTF', 'OTF', 'WOFF2')]
[string[]]$Type = @('TTF', 'OTF', 'WOFF2'),
[Parameter(Mandatory = $true, ParameterSetName = 'ByAll')]
[switch]$All,
[Parameter(Mandatory = $false, ParameterSetName = 'ListOnly', HelpMessage = 'List available Nerd Fonts matching the specified pattern.')]
[AllowNull()]
[AllowEmptyString()]
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
@('All') | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
})]
[string]$List,
[Parameter(Mandatory = $false, ParameterSetName = 'ByAll', HelpMessage = 'In which scope do you want to install the Nerd Font, AllUsers or CurrentUser?')]
[Parameter(Mandatory = $false, ParameterSetName = 'ByName', HelpMessage = 'In which scope do you want to install the Nerd Font, AllUsers or CurrentUser?')]
[ValidateSet('AllUsers', 'CurrentUser')]
[string]$Scope = 'CurrentUser',
[Parameter(Mandatory = $false, ParameterSetName = 'ByAll')]
[Parameter(Mandatory = $false, ParameterSetName = 'ByName')]
[switch]$Force,
[Parameter(Mandatory = $true, ParameterSetName = 'Help', HelpMessage = "What kind of help would you like to see?")]
[AllowEmptyString()]
[AllowNull()]
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$helpOptions = @{
Name = "Shows help for the dynamic Name parameter."
Variant = "Shows help for the Variant parameter."
Type = "Shows help for the Type parameter."
All = "Shows help for the All parameter."
List = "Shows help for the List parameter."
Scope = "Shows help for the Scope parameter."
Force = "Shows help for the Force parameter."
Help = "Shows help for the Help parameter."
Version = "Shows help for the Version parameter."
Summary = "Provides a summary of the help content. Note that the dynamic Name parameter is not included in the summary."
Detailed = "Provides detailed help, including parameter descriptions and examples. Note that the dynamic Name parameter is not included in the detailed help."
Full = "Provides full help, including detailed help, parameter descriptions, examples, and additional notes. Note that the dynamic Name parameter is not included in the full help."
Examples = "Shows only the examples section of the help."
}
$helpOptions.GetEnumerator() | Where-Object { $_.Key -like "$wordToComplete*" } | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.Key, $_.Key, 'ParameterValue', $_.Value)
}
})]
[string]$Help = 'Help',
[Parameter(Mandatory = $true, ParameterSetName = 'Version')]
[switch]$Version
)
dynamicparam {
# Define the URL and cache file path
$url = 'https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/bin/scripts/lib/fonts.json'
$cacheFilePath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'github-nerd-fonts.json')
$cacheDuration = [TimeSpan]::FromMinutes(2)
#region Functions ==========================================================
function Get-FontsListFromWeb {
<#
.SYNOPSIS
Fetch fonts list from the web server.
.DESCRIPTION
This function fetches the fonts list from the specified web server URL.
It also adds a release URL property to each font object.
#>
try {
$fonts = (Invoke-RestMethod -Uri $url -ErrorAction Stop -Verbose:$false -Debug:$false).fonts
$releaseUrl = "https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest"
foreach ($font in $fonts) {
$font.PSObject.Properties.Add([PSNoteProperty]::new("releaseUrl", $releaseUrl))
}
return $fonts
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
function Get-FontsListFromCache {
<#
.SYNOPSIS
Load fonts list from cache.
.DESCRIPTION
This function loads the fonts list from a cache file if it exists and is not expired.
#>
if ([System.IO.Directory]::Exists($cacheFilePath)) {
$cacheFile = Get-Item $cacheFilePath
if ((Get-Date) -lt $cacheFile.LastWriteTime.Add($cacheDuration)) {
return Get-Content $cacheFilePath | ConvertFrom-Json
}
}
return $null
}
function Save-FontsListToCache($fonts) {
<#
.SYNOPSIS
Save fonts list to cache.
.DESCRIPTION
This function saves the fonts list to a cache file in JSON format.
#>
$fonts | ConvertTo-Json | Set-Content $cacheFilePath
}
function Add-CustomEntries($fonts) {
<#
.SYNOPSIS
Add custom entries to the fonts list.
.DESCRIPTION
This function adds custom font entries to the provided fonts list and sorts them by folder name.
#>
$customEntries = @(
[PSCustomObject]@{
unpatchedName = 'Cascadia Code Font Family'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Code Font Family'
folderName = 'CascadiaCode'
imagePreviewFont = 'Cascadia Code Font Family'
imagePreviewFontSource = $null
linkPreviewFont = 'cascadia-code'
caskName = 'cascadia-code'
repoRelease = $false
description = 'The official Cascadia Code font by Microsoft with all variants, including Nerd Font and Powerline'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
},
[PSCustomObject]@{
unpatchedName = 'Cascadia Code NF'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Code NF'
folderName = 'CascadiaCodeNF'
imagePreviewFont = 'Cascadia Code Nerd Font'
imagePreviewFontSource = $null
linkPreviewFont = 'cascadia-code'
caskName = 'cascadia-code-nerd-font'
repoRelease = $false
description = 'The official Cascadia Code font by Microsoft that is enabled with Nerd Font symbols'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
},
[PSCustomObject]@{
unpatchedName = 'Cascadia Code PL'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Code PL'
folderName = 'CascadiaCodePL'
imagePreviewFont = 'Cascadia Code Powerline Font'
imagePreviewFontSource = $null
linkPreviewFont = 'cascadia-code'
caskName = 'cascadia-code-powerline-font'
repoRelease = $false
description = 'The official Cascadia Code font by Microsoft that is enabled with Powerline symbols'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
},
[PSCustomObject]@{
unpatchedName = 'Cascadia Mono Font Family'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Mono Font Family'
folderName = 'CascadiaMono'
imagePreviewFont = 'Cascadia Mono Font Family'
imagePreviewFontSource = $null
linkPreviewFont = $null
caskName = 'cascadia-mono'
repoRelease = $false
description = 'The official Cascadia Mono font by Microsoft with all variants, including Nerd Font and Powerline'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
},
[PSCustomObject]@{
unpatchedName = 'Cascadia Mono NF'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Mono NF'
folderName = 'CascadiaMonoNF'
imagePreviewFont = 'Cascadia Mono Nerd Font'
imagePreviewFontSource = $null
linkPreviewFont = $null
caskName = 'cascadia-mono-nerd-font'
repoRelease = $false
description = 'The official Cascadia Mono font by Microsoft that is enabled with Nerd Font symbols'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
},
[PSCustomObject]@{
unpatchedName = 'Cascadia Mono PL'
licenseId = 'OFL-1.1-RFN'
RFN = $true
version = 'latest'
patchedName = 'Cascadia Mono PL'
folderName = 'CascadiaMonoPL'
imagePreviewFont = 'Cascadia Mono Powerline Font'
imagePreviewFontSource = $null
linkPreviewFont = $null
caskName = 'cascadia-mono-powerline-font'
repoRelease = $false
description = 'The official Cascadia Mono font by Microsoft that is enabled with Powerline symbols'
releaseUrl = 'https://api.github.com/repos/microsoft/cascadia-code/releases/latest'
}
)
# Combine the original fonts with custom entries and sort by folderName
$allFonts = $fonts + $customEntries
$sortedFonts = $allFonts | Sort-Object -Property caskName
return $sortedFonts
}
#endregion Functions -------------------------------------------------------
# Try to load fonts list from cache
$allNerdFonts = Get-FontsListFromCache
# If cache is not valid, fetch from web, add custom entries, and update cache
if (-not $allNerdFonts) {
$allNerdFonts = Get-FontsListFromWeb
$allNerdFonts = Add-CustomEntries $allNerdFonts
Save-FontsListToCache $allNerdFonts
}
# Extract caskName values for auto-completion
$caskNames = [string[]]@($allNerdFonts | ForEach-Object { $_.caskName })
# Define the name and type of the dynamic parameter
$paramName = 'Name'
$paramType = [string[]]
# Create a collection to hold the attributes for the dynamic parameter
$attributes = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
# Convert the caskNames array to a string representation
$caskNamesString = $caskNames -join "', '"
$caskNamesString = "@('$caskNamesString')"
# Create an ArgumentCompleter attribute using the caskName values for auto-completion and add it to the collection
$argumentCompleterScript = [scriptblock]::Create(@"
param(`$commandName, `$parameterName, `$wordToComplete, `$commandAst, `$fakeBoundParameter)
# Static array of cask names for auto-completion
`$caskNames = $caskNamesString
# Filter and return matching cask names
`$caskNames | Where-Object { `$_ -like "`$wordToComplete*" } | ForEach-Object {
[System.Management.Automation.CompletionResult]::new(`$_, `$_, 'ParameterValue', `$_)
}
"@)
$argumentCompleterAttribute = [System.Management.Automation.ArgumentCompleterAttribute]::new($argumentCompleterScript)
$attributes.Add($argumentCompleterAttribute)
# Create a Parameter attribute and add it to the collection
$paramAttribute = [System.Management.Automation.ParameterAttribute]::new()
$paramAttribute.Mandatory = $(
# Make the parameter mandatory if the script is not running interactively
if (
$null -ne ([System.Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^-NonI.*' }) -or
(
$null -ne ([System.Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^-C.*' }) -and
$null -eq ([System.Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^-NoE.*' })
)
) {
$true
}
elseif ($Host.UI.RawUI.KeyAvailable -or [System.Environment]::UserInteractive) {
$false
}
else {
$true
}
)
$paramAttribute.Position = 0
$paramAttribute.ParameterSetName = 'ByName'
$paramAttribute.HelpMessage = 'Which Nerd Font do you want to install?' + "`n" + "Available values: $($caskNames -join ', ')"
$paramAttribute.ValueFromPipeline = $true
$paramAttribute.ValueFromPipelineByPropertyName = $true
$attributes.Add($paramAttribute)
# Create the dynamic parameter
$runtimeParam = [System.Management.Automation.RuntimeDefinedParameter]::new($paramName, $paramType, $attributes)
# Create a dictionary to hold the dynamic parameters
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$paramDictionary.Add($paramName, $runtimeParam)
# Return the dictionary
return $paramDictionary
}
begin {
if (
$PSBoundParameters.ContainsKey('Help') -or
(
$PSBoundParameters.Name.Count -eq 1 -and
@('help', '--help', '?') -contains $PSBoundParameters.Name[0]
)
) {
try {
if ($null -eq $PSCommandPath -or $PSCommandPath -eq '') {
$scriptContent = $MyInvocation.MyCommand.ScriptBlock.ToString()
$tempFilePath = [System.IO.Path]::GetTempFileName()
$tempPs1FilePath = $tempFilePath + '.ps1'
Write-Verbose "Creating temporary file: $tempPs1FilePath"
Set-Content -Path $tempPs1FilePath -Value $scriptContent
}
else {
$tempFilePath = $PSCommandPath
$tempPs1FilePath = $tempFilePath
}
# Use Get-Help to render the help content
$params = @{ Name = $tempPs1FilePath }
if ([string]::IsNullOrEmpty($Help)) {
$params.Parameter = 'Help'
}
elseif ($Help -ne 'Summary') {
if (@('Detailed', 'Full', 'Examples') -contains $Help) {
$params.$Help = $true
}
elseif (@('Variant', 'Type', 'All', 'List', 'Scope', 'Force', 'Help', 'Version') -contains $Help) {
$params.Parameter = $Help
}
elseif ($Help -eq 'Name') {
$scriptContent = $MyInvocation.MyCommand.ScriptBlock.ToString()
$helpContent = @()
$inHelpBlock = $false
$helpBlockFound = $false
$inParameterNameSection = $false
foreach ($line in $scriptContent -split "`n") {
if ($line -match '^\s*<#' -and -not $helpBlockFound) {
if ($line -notmatch '^\s*<#PSScriptInfo') {
$inHelpBlock = $true
}
}
if ($inHelpBlock) {
if ($line -match '^\s*\.PARAMETER\s+Name\s*$') {
$inParameterNameSection = $true
}
elseif ($line -match '^\s*\.PARAMETER\s+' -and $inParameterNameSection) {
$inParameterNameSection = $false
}
if ($inParameterNameSection) {
$helpContent += $line
}
}
if ($line -match '#>\s*$' -and $inHelpBlock) {
$inHelpBlock = $false
$helpBlockFound = $true
}
if ($helpBlockFound -and -not $inHelpBlock) {
break
}
}
if ($helpContent) {
Write-Output ''
$helpContent[0] = '-Name <String[]>'
$helpText = $helpContent -join "`n"
Write-Output $helpText
Write-Output ''
Write-Output ' Required? true (unless running in an interactive session to display the selection menu)'
Write-Output ' Position? 0'
Write-Output ' Default value'
Write-Output ' Accept pipeline input? true (ByValue, ByPropertyName)'
Write-Output ' Accept wildcard characters? false'
Write-Output ''
Write-Output ''
Write-Output ''
}
else {
Write-Output "No .PARAMETER Name content found."
}
return
}
else {
$params.Parameter = 'Help'
}
}
Get-Help @params
}
finally {
if ($null -eq $PSCommandPath -or $PSCommandPath -eq '') {
Write-Verbose "Removing temporary files: $tempFilePath, $tempPs1FilePath"
Remove-Item -Path $tempFilePath -Force
Remove-Item -Path $tempPs1FilePath -Force
}
}
return
}
if (
$Version -or
(
$PSBoundParameters.Name.Count -eq 1 -and
@('version', '--version', 'ver') -eq $PSBoundParameters.Name[0]
)
) {
$scriptContent = $MyInvocation.MyCommand.ScriptBlock.ToString()
$versionNumber = $null
$inHelpBlock = $false
$helpBlockFound = $false
foreach ($line in $scriptContent -split "`n") {
if ($line -match '^\s*<#PSScriptInfo' -and -not $helpBlockFound) {
$inHelpBlock = $true
}
if ($inHelpBlock) {
if ($line -match '^\s*\.VERSION\s+(.+)$') {
$versionNumber = $Matches[1].Trim()
break
}
}
if ($line -match '#>\s*$' -and $inHelpBlock) {
$inHelpBlock = $false
$helpBlockFound = $true
}
}
if ($versionNumber) {
Write-Output $versionNumber
}
else {
Write-Output "No version information found."
}
return
}
if ($PSBoundParameters.ContainsKey('List')) {
# Set default value if List is null or empty
if ([string]::IsNullOrEmpty($List)) {
$List = "*"
}
else {
$List = $List.Trim()
}
# Handle special case for 'All'
if ($List -eq 'All') {
$List = "*"
}
elseif ($List -notmatch '\*') {
# Ensure the List contains wildcard characters
$List = "*$List*"
}
# Filter and format the output
$allNerdFonts | Where-Object { $_.caskName -like $List } | ForEach-Object {
[PSCustomObject]@{
Name = $_.caskName
DisplayName = $_.imagePreviewFont
Description = $_.description
SourceUrl = $_.releaseUrl -replace '^(https?://)(?:[^/]+\.)*([^/]+\.[^/]+)/repos/([^/]+)/([^/]+).*', '$1$2/$3/$4'
}
}
return
}
if (
$null -ne $env:REMOTE_CONTAINERS -or
$null -ne $env:CODESPACES -or
$null -ne $env:WSL_INTEROP
) {
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
[System.Exception]::new('This script must be run on your local machine, not in a container.'),
'NotLocalMachine',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
$null
)
)
}
if (
$Scope -eq 'AllUsers' -and
(
(
$PSVersionTable.Platform -ne 'Unix' -and
-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')
) -or
(
$PSVersionTable.Platform -eq 'Unix' -and
($(id -u) -ne '0')
)
)
) {
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
[System.Exception]::new('Elevated permissions are required to install fonts for all users. Alternatively, you can install fonts for the current user using the -Scope parameter with the CurrentUser value.'),
'InsufficientPermissions',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
$null
)
)
}
#region Functions ==========================================================
function Show-Menu {
<#
.SYNOPSIS
Displays a menu for selecting fonts.
.DESCRIPTION
This function clears the host and displays a menu with options for selecting fonts.
It handles user input and terminal resizing to dynamically adjust the menu display.
#>
param (
$Options
)
Clear-Host
function Show-MenuOptions {
<#
.SYNOPSIS
Draws the menu options.
.DESCRIPTION
This function prints the menu options in a formatted manner.
It calculates the number of columns and rows based on the terminal width and displays the options accordingly.
#>
param (
$Options,
$terminalWidth
)
# Add the 'All Fonts' option at the top
$Options = @([pscustomobject]@{ imagePreviewFont = 'All Fonts'; unpatchedName = 'All'; caskName = 'All' }) + $Options
# Calculate the maximum width of each column
$maxOptionLength = ($Options | ForEach-Object { $_.imagePreviewFont.Length } | Measure-Object -Maximum).Maximum + 1 # 1 for padding
$maxIndexLength = ($Options.Length).ToString().Length
$linkSymbolLength = 1
$columnWidth = $maxIndexLength + $maxOptionLength + $linkSymbolLength + 3 # 3 for padding and ': '
# Calculate the number of columns that can fit in the terminal width
$numColumns = [math]::Floor($terminalWidth / $columnWidth)
# Calculate the number of rows
$numRows = [math]::Ceiling($Options.Length / $numColumns)
# Print the centered and bold title
if ($IsCoreCLR) {
$title = "`u{1F913} $($PSStyle.Bold)`e]8;;https://www.nerdfonts.com/`e\Nerd Fonts`e]8;;`e\ Installation$($PSStyle.BoldOff)"
}
else {
$title = 'Nerd Fonts Installation'
}
$totalWidth = $columnWidth * $numColumns
$padding = [math]::Max(0, ($totalWidth - ($title.Length / 2)) / 2)
Write-Host (' ' * $padding + $title) -ForegroundColor Cyan -NoNewline
Write-Host -ForegroundColor Cyan
Write-Host (('_' * $totalWidth) + "`n") -ForegroundColor Cyan
# Print the options in rows
for ($row = 0; $row -lt $numRows; $row++) {
for ($col = 0; $col -lt $numColumns; $col++) {
$index = $row + $col * $numRows
if ($index -lt $Options.Length) {
$number = $index
$fontName = $Options[$index].imagePreviewFont
$numberText = ('{0,' + $maxIndexLength + '}') -f $number
$linkSymbol = "`u{2197}" # Up-Right Arrow
if ($index -eq 0) {
# Special formatting for 'All Fonts'
Write-Host -NoNewline -ForegroundColor Magenta $numberText
Write-Host -NoNewline -ForegroundColor Magenta ': '
Write-Host -NoNewline -ForegroundColor Magenta "$($PSStyle.Italic)$fontName$($PSStyle.ItalicOff) "
}
else {
Write-Host -NoNewline -ForegroundColor DarkYellow $numberText
Write-Host -NoNewline -ForegroundColor Yellow ': '
if ($fontName -match '^(.+)(Font Family)(.*)$') {
if ($IsCoreCLR -and $Options[$index].linkPreviewFont -is [string] -and -not [string]::IsNullOrEmpty($Options[$index].linkPreviewFont)) {
$link = $Options[$index].linkPreviewFont
if ($link -notmatch '^https?://') {
$link = "https://www.programmingfonts.org/#$link"
}
$clickableLinkSymbol = " `e]8;;$link`e\$linkSymbol`e]8;;`e\"
Write-Host -NoNewline -ForegroundColor White "$($PSStyle.Bold)$($Matches[1])$($PSStyle.BoldOff)"
Write-Host -NoNewline -ForegroundColor Gray "$($PSStyle.Italic)$($Matches[2])$($PSStyle.ItalicOff)"
Write-Host -NoNewline -ForegroundColor White "$($Matches[3])"
Write-Host -NoNewline -ForegroundColor DarkBlue "$clickableLinkSymbol"
}
else {
Write-Host -NoNewline -ForegroundColor White "$($PSStyle.Bold)$($Matches[1])$($PSStyle.BoldOff)"
Write-Host -NoNewline -ForegroundColor Gray "$($PSStyle.Italic)$($Matches[2])$($PSStyle.ItalicOff)"
Write-Host -NoNewline -ForegroundColor White "$($Matches[3]) "
}
}
else {
if ($IsCoreCLR -and $Options[$index].linkPreviewFont -is [string] -and -not [string]::IsNullOrEmpty($Options[$index].linkPreviewFont)) {
$link = $Options[$index].linkPreviewFont
if ($link -notmatch '^https?://') {
$link = "https://www.programmingfonts.org/#$link"
}
$clickableLinkSymbol = " `e]8;;$link`e\$linkSymbol`e]8;;`e\"
Write-Host -NoNewline -ForegroundColor White "$($PSStyle.Bold)$fontName$($PSStyle.BoldOff)"
Write-Host -NoNewline -ForegroundColor DarkBlue "$clickableLinkSymbol"
}
else {
Write-Host -NoNewline -ForegroundColor White "$($PSStyle.Bold)$fontName$($PSStyle.BoldOff) "
}
}
}
# Add padding to align columns
$paddingLength = $maxOptionLength - $fontName.Length
Write-Host -NoNewline (' ' * $paddingLength)
}
}
Write-Host
}
}
# Initial terminal width
$initialWidth = [console]::WindowWidth
# Draw the initial menu
Show-MenuOptions -Options $Options -terminalWidth $initialWidth
Write-Host "`nEnter 'q' to quit." -ForegroundColor Cyan
# Loop to handle user input and terminal resizing
while ($true) {
$currentWidth = [console]::WindowWidth
if ($currentWidth -ne $initialWidth) {
Clear-Host
Show-MenuOptions -Options $Options -terminalWidth $currentWidth
Write-Host "`nEnter 'q' to quit." -ForegroundColor Cyan
$initialWidth = $currentWidth
}
$selection = Read-Host "`nSelect one or more numbers separated by commas"
if ($selection -eq 'q') {
return 'quit'
}
# Remove spaces and split the input by commas
$selection = $selection -replace '\s', ''
$numbers = $selection -split ',' | Select-Object -Unique
# Validate each number
$validSelections = @()
$invalidSelections = @()
foreach ($number in $numbers) {
if ($number -match '^-?\d+$') {
$index = [int]$number - 1
if ($index -lt 0) {
return 'All'
}
elseif ($index -ge 0 -and $index -lt $Options.Count) {
$validSelections += $Options[$index]
}
else {
$invalidSelections += $number
}
}
else {
$invalidSelections += $number
}
}
if ($invalidSelections.Count -eq 0) {
return $validSelections.caskName
}
else {
Write-Host "Invalid selection(s): $($invalidSelections -join ', '). Please enter valid numbers between 0 and $($Options.Length) or 'q' to quit." -ForegroundColor Red
}
}
}
function Invoke-GitHubApiRequest {
<#
.SYNOPSIS
Makes anonymous requests to GitHub API and handles rate limiting.
.DESCRIPTION
This function sends a request to the specified GitHub API URI and handles rate limiting by retrying the request
up to a maximum number of retries. It also converts JSON responses to PowerShell objects.
#>
param (
[string]$Uri
)
$maxRetries = 5
$retryCount = 0
$baseWaitTime = 15
while ($retryCount -lt $maxRetries) {
try {
$headers = @{}
$parsedUri = [System.Uri]$Uri
if ($parsedUri.Host -eq "api.github.com") {
$headers["Accept"] = "application/vnd.github.v3+json"
}
$response = Invoke-RestMethod -Uri $Uri -Headers $headers -ErrorAction Stop -Verbose:$false -Debug:$false
return [PSCustomObject]@{
Headers = $response.PSObject.Properties["Headers"].Value
Content = $response
}
}
catch {
if ($_.Exception.Response.StatusCode -eq 403 -or $_.Exception.Response.StatusCode -eq 429) {
$retryAfter = $null
$rateLimitReset = $null
$waitTime = 0
if ($_.Exception.Response.Headers -and $_.Exception.Response.Headers["Retry-After"]) {
$retryAfter = $_.Exception.Response.Headers["Retry-After"]
}
if ($_.Exception.Response.Headers -and $_.Exception.Response.Headers["X-RateLimit-Reset"]) {
$rateLimitReset = $_.Exception.Response.Headers["X-RateLimit-Reset"]
}
if ($retryAfter) {
$waitTime = [int]$retryAfter
}
elseif ($rateLimitReset) {
$resetTime = [DateTimeOffset]::FromUnixTimeSeconds([int]$rateLimitReset).LocalDateTime
$waitTime = ($resetTime - (Get-Date)).TotalSeconds
}
if ($waitTime -gt 0 -and $waitTime -le 60) {
Write-Host "Rate limit exceeded. Waiting for $waitTime seconds."
Start-Sleep -Seconds $waitTime
}
else {
$exponentialWait = $baseWaitTime * [math]::Pow(2, $retryCount)
Write-Host "Rate limit exceeded. Waiting for $exponentialWait seconds."
Start-Sleep -Seconds $exponentialWait
}
$retryCount++
}
else {
$PSCmdlet.ThrowTerminatingError($_)
}
}
}
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
[System.Exception]::new('Max retries exceeded. Please try again later.'),
'MaxRetriesExceeded',
[System.Management.Automation.ErrorCategory]::ResourceUnavailable,
$null
)
)
}
function Invoke-GitHubApiPaginatedRequest {
<#
.SYNOPSIS
Fetches all pages of a paginated response if the host is api.github.com.
.DESCRIPTION
This function sends requests to the specified GitHub API URI and handles pagination by following the 'next' links
in the response headers. It collects all pages of data and returns them as a single array.
#>
param (
[string]$Uri
)
$allData = @()
$parsedUri = [System.Uri]$Uri
if ($parsedUri.Host -eq "api.github.com") {
while ($true) {
$response = Invoke-GitHubApiRequest -Uri $Uri
if ($null -eq $response) {
break
}
$data = $response.Content
$allData += $data
$linkHeader = $null
if ($response.Headers -and $response.Headers["Link"]) {
$linkHeader = $response.Headers["Link"]
}
if ($linkHeader -notmatch 'rel="next"') {
break
}
$nextLink = ($linkHeader -split ',') | Where-Object { $_ -match 'rel="next"' } | ForEach-Object { ($_ -split ';')[0].Trim('<> ') }
$Uri = $nextLink
}
}
else {
$response = Invoke-GitHubApiRequest -Uri $Uri