-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathinstall.ps1
More file actions
615 lines (512 loc) · 21.7 KB
/
install.ps1
File metadata and controls
615 lines (512 loc) · 21.7 KB
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
#Requires -RunAsAdministrator
#Requires -Version 7.0
<#
.SYNOPSIS
Automated install script for Powershell & Windows terminal
.DESCRIPTION
Installs and configures a PS7, Windows Terminal, and various PowerShell modules and fonts - baseline for winget installs
.PARAMETER SkipModules
Skip PowerShell module installation (default: $false)
.EXAMPLE
.\Install.ps1
Run standard installation
.EXAMPLE
.\Install.ps1 -SkipModules
Run installation without PowerShell modules installs
#>
[CmdletBinding()]
param(
[ValidateSet('Install','Uninstall')]
[string]$Mode = 'Install',
[switch]$SkipModules,
[switch]$Interactive
)
# Global configuration
$script:Config = @{
BackupPath = "$env:USERPROFILE\PowerShellSetupBackup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
AssetsPath = "$env:USERPROFILE\AppData\Local\PowerShellTerminalAssets"
}
# Logging functions
function Write-StatusLine {
param(
[Parameter(Mandatory)]
[string]$Message,
[ValidateSet('Success', 'Error', 'AlreadyInstalled')]
[string]$Status,
[switch]$IsSubStep,
[string]$AdditionalInfo = ""
)
# Fixed width for all lines
$totalWidth = 70
$prefix = if ($IsSubStep) { " └─ " } else { "" }
$fullMessage = "$prefix$Message"
# statuses
$baseStatusText = switch ($Status) {
'Success' { "✓" }
'Error' { "✗" }
'AlreadyInstalled' { "✓" }
}
$statusText = $baseStatusText
if ($AdditionalInfo -and $Status -eq 'AlreadyInstalled') {
$statusText += " ($AdditionalInfo)"
}
# Calculate the position where status should start (same for all lines)
$statusStartPos = $totalWidth - $baseStatusText.Length
# Calculate dots needed to reach that position
$dotsNeeded = $statusStartPos - $fullMessage.Length
if ($dotsNeeded -lt 1) { $dotsNeeded = 1 }
$dots = "." * $dotsNeeded
$messageColor = if ($IsSubStep) { 'DarkGray' } else { 'White' }
Write-Host $fullMessage -NoNewline -ForegroundColor $messageColor
Write-Host $dots -NoNewline -ForegroundColor DarkGray
$statusColor = switch ($Status) {
'Success' { 'Green' }
'Error' { 'Red' }
'AlreadyInstalled' { 'Green' }
}
Write-Host $statusText -ForegroundColor $statusColor
}
function Install-WinGet {
Write-Host ""
Write-Host " Installing WinGet package manager" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing WinGet package manager".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
$hasPackageManager = Get-AppPackage -Name "Microsoft.DesktopAppInstaller" -ErrorAction SilentlyContinue
$hasWingetExe = Test-Path "C:\Users\$env:Username\AppData\Local\Microsoft\WindowsApps\winget.exe"
if (-not $hasPackageManager -or -not $hasWingetExe) {
$releases_url = "https://api.github.com/repos/microsoft/winget-cli/releases/latest"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$releases = Invoke-RestMethod -Uri $releases_url -ErrorAction Stop
$latestRelease = $releases.assets | Where-Object { $_.browser_download_url.EndsWith("msixbundle") } | Select-Object -First 1
if (-not $latestRelease) {
throw "Could not find WinGet"
}
Add-AppxPackage -Path $latestRelease.browser_download_url -ErrorAction Stop
Write-Host " ✓" -ForegroundColor Green
} else {
Write-Host " ✓ (Already installed)" -ForegroundColor Green
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Install-WindowsTerminal {
Write-Host " Installing Windows Terminal" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing Windows Terminal".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
$hasWindowsTerminal = Get-AppPackage -Name "Microsoft.WindowsTerminal" -ErrorAction SilentlyContinue
if (-not $env:WT_SESSION -or -not $hasWindowsTerminal) {
$result = winget install --id=Microsoft.WindowsTerminal -e --accept-package-agreements --accept-source-agreements --silent
# seems -1978335189 is the "alrady installed" exit code from WinGet so will skip if we get that
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne -1978335189) {
throw "WinGet installation failed with exit code $LASTEXITCODE"
}
Write-Host " ✓" -ForegroundColor Green
} else {
Write-Host " ✓ (Already installed)" -ForegroundColor Green
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Install-Fonts {
Write-Host " Installing Nerd Fonts" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing Nerd Fonts".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
$fontsToInstallDirectory = ".\assets\fonts\"
if (-not (Test-Path $fontsToInstallDirectory)) {
return $false
}
$fontsToInstall = Get-ChildItem "$fontsToInstallDirectory*.ttf" -ErrorAction SilentlyContinue
if (-not $fontsToInstall) {
return $false
}
# Use system fonts directory for installation
$systemFontsDir = "$env:WINDIR\Fonts"
$userFontsDir = "$env:USERPROFILE\AppData\Local\Microsoft\Windows\Fonts"
if (-not (Test-Path $userFontsDir)) {
New-Item -Path $userFontsDir -ItemType Directory -Force | Out-Null
}
$installedCount = 0
foreach ($font in $fontsToInstall) {
$fontName = $font.Name
$fontPath = $font.FullName
# Check if fonts are already installed
$systemFontExists = Test-Path "$systemFontsDir\$fontName"
$userFontExists = Test-Path "$userFontsDir\$fontName"
if (-not $systemFontExists -and -not $userFontExists) {
try {
# Try system installation first
Copy-Item $fontPath -Destination $systemFontsDir -Force -ErrorAction Stop
# Register font in registry
$fontDisplayName = [System.IO.Path]::GetFileNameWithoutExtension($fontName)
$regPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
New-ItemProperty -Path $regPath -Name "$fontDisplayName (TrueType)" -Value $fontName -PropertyType String -Force | Out-Null
$installedCount++
}
catch {
# Fallback to user installation if abive fails
try {
Copy-Item $fontPath -Destination $userFontsDir -Force
# Register font in user registry
$fontDisplayName = [System.IO.Path]::GetFileNameWithoutExtension($fontName)
$regPath = "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
if (-not (Test-Path $regPath)) {
New-Item -Path $regPath -Force | Out-Null
}
New-ItemProperty -Path $regPath -Name "$fontDisplayName (TrueType)" -Value "$userFontsDir\$fontName" -PropertyType String -Force | Out-Null
$installedCount++
}
catch {
}
}
}
}
if ($installedCount -gt 0) {
Write-Host " ✓" -ForegroundColor Green
} else {
Write-Host " ✓ (Already installed)" -ForegroundColor Green
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Set-PSRepository {
#Write-Host "Configuring PowerShell Gallery as trusted repository" -NoNewline -ForegroundColor White
#$dots = "." * (70 - "Configuring PowerShell Gallery as trusted repository".Length - 2)
#Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
# Check if PSGallery is already trusted
$psGallery = Get-PSRepository -Name 'PSGallery' -ErrorAction SilentlyContinue
if ($psGallery -and $psGallery.InstallationPolicy -eq 'Trusted') {
#Write-Host " ✓ (Already trusted)" -ForegroundColor Green
return $true
}
# Check if NuGet already available
$nugetProvider = Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue
if (-not $nugetProvider) {
$job = Start-Job -ScriptBlock {
Install-PackageProvider -Name NuGet -Force -Scope CurrentUser -Confirm:$false
}
$completed = Wait-Job $job -Timeout 60
if ($completed) {
Receive-Job $job | Out-Null
Remove-Job $job -Force
} else {
Remove-Job $job -Force
throw "NuGet provider installation timed out after 60 seconds"
}
}
# Set PSGallery as trusted
$job = Start-Job -ScriptBlock {
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
}
$completed = Wait-Job $job -Timeout 60
if ($completed) {
Receive-Job $job | Out-Null
Remove-Job $job -Force
#Write-Host " ✓" -ForegroundColor Green
return $true
} else {
Remove-Job $job -Force
throw "PSGallery configuration timed out after 60 seconds"
}
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Install-OhMyPosh {
Write-Host " Installing Oh-My-Posh" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing Oh-My-Posh".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
$result = winget install JanDeDobbeleer.OhMyPosh --accept-package-agreements --accept-source-agreements --silent
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne -1978335189) {
throw "WinGet installation failed with exit code $LASTEXITCODE"
}
# Install my theme
$themeDest = "C:\Users\$env:Username\AppData\Local\Programs\oh-my-posh\themes"
if (-not (Test-Path $themeDest)) {
New-Item -Path $themeDest -ItemType Directory -Force | Out-Null
}
$themeSource = ".\configs\oh-my-posh\themes\wylde.omp.json"
if (Test-Path $themeSource) {
Copy-Item $themeSource -Destination $themeDest -Force
# theme installed
} else {
# theme not fuond
}
Write-Host " ✓" -ForegroundColor Green
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Install-PowerShellModules {
Write-Host " Installing PowerShell modules" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing PowerShell modules".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
if ($SkipModules) {
Write-Host " ✓ (Skipped)" -ForegroundColor Green
return $true
}
Write-Host " ✓" -ForegroundColor Green
$modules = @(
@{ Name = 'z'; Version = '1.1.3' } # pinned
@{ Name = 'Terminal-Icons'; Version = $null } # latest is fine
@{ Name = 'PSReadLine'; Version = '2.2.6'; Prerelease = $true } # pinnde
)
try {
$psExe = "pwsh.exe"
foreach ($module in $modules) {
# Check if module is already installed (not sure if useful or not... probably cut)
$checkCommand = "Get-Module -Name '$($module.Name)' -ListAvailable"
$existingModule = & $psExe -Command $checkCommand 2>$null
if ($existingModule) {
Write-StatusLine "Installing module: $($module.Name)" -Status 'AlreadyInstalled' -IsSubStep -AdditionalInfo "Already installed"
continue
}
# Build installs
if ($module.Version) {
$installCommand = "Install-Module -Name '$($module.Name)' -RequiredVersion '$($module.Version)' -Force -Scope CurrentUser -AllowClobber"
} else {
$installCommand = "Install-Module -Name '$($module.Name)' -Force -Scope CurrentUser -AllowClobber"
}
if ($module.Prerelease) {
$installCommand += " -AllowPrerelease -SkipPublisherCheck"
}
# Execute
$job = Start-Job -ScriptBlock ([scriptblock]::Create("& '$psExe' -Command `"$installCommand`""))
$completed = Wait-Job $job -Timeout 300
if ($completed) {
#$output = Receive-Job $job
#$error = Receive-Job $job -ErrorVariable jobErrors
if ($job.State -eq 'Completed' -and -not $jobErrors) {
Write-StatusLine "Installing module: $($module.Name)" -Status 'Success' -IsSubStep
} else {
Write-StatusLine "Installing module: $($module.Name)" -Status 'Error' -IsSubStep
}
} else {
Write-StatusLine "Installing module: $($module.Name)" -Status 'Error' -IsSubStep
}
Remove-Job $job -Force
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Set-PowerShellProfile {
Write-Host " Configuring PowerShell profile" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Configuring PowerShell profile".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
# Backup existing profile
if (Test-Path $PROFILE) {
$backupName = "Microsoft.PowerShell_profile.ps1.backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
$backupPath = Join-Path (Split-Path $PROFILE) $backupName
Copy-Item $PROFILE -Destination $backupPath
}
# Ensure profile directory exists
$profileDir = Split-Path $PROFILE
if (-not (Test-Path $profileDir)) {
New-Item -Path $profileDir -ItemType Directory -Force | Out-Null
}
# Copy new profile
$profileSource = ".\configs\powershell\Microsoft.PowerShell_profile.ps1"
if (Test-Path $profileSource) {
Copy-Item $profileSource -Destination $PROFILE -Force
# Unblock the profile
try {
Unblock-File -Path $PROFILE -ErrorAction SilentlyContinue
}
catch {
# carry on - should probably check if this is needed
}
Write-Host " ✓" -ForegroundColor Green
} else {
Write-Host " ✗" -ForegroundColor Red
return $false
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Set-WindowsTerminalConfig {
Write-Host " Configuring Windows Terminal" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Configuring Windows Terminal".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
try {
# Create assets directory and copy icons - leftovers from my own version with custom profiles and icons, could probably remove the icon assets
if (-not (Test-Path $script:Config.AssetsPath)) {
New-Item -Path $script:Config.AssetsPath -ItemType Directory -Force | Out-Null
}
$iconsSource = ".\assets\icons"
if (Test-Path $iconsSource) {
Get-ChildItem "$iconsSource\*.png" | Copy-Item -Destination $script:Config.AssetsPath -Force
}
# build wt paths from user env vars
$terminalConfigPath = "$env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState"
if (-not (Test-Path $terminalConfigPath)) {
New-Item -Path $terminalConfigPath -ItemType Directory -Force | Out-Null
}
# change paths in settings.json
$settingsSource = ".\configs\terminal\settings.json"
if (Test-Path $settingsSource) {
$settingsContent = Get-Content $settingsSource -Raw | ConvertFrom-Json
# Update paths to use the assets directory
foreach ($profile in $settingsContent.profiles.list) {
if ($profile.icon -and $profile.icon.StartsWith("C:\temp\wt_assets\")) {
$iconName = Split-Path $profile.icon -Leaf
$profile.icon = Join-Path $script:Config.AssetsPath $iconName
}
if ($profile.backgroundImage -and $profile.backgroundImage.StartsWith("C:\temp\wt_assets\")) {
$iconName = Split-Path $profile.backgroundImage -Leaf
$profile.backgroundImage = Join-Path $script:Config.AssetsPath $iconName
}
if ($profile.startingDirectory -eq "C:\Users\") {
$profile.startingDirectory = "$env:USERPROFILE\Documents"
}
}
# Update lab script path - probs needs cutting too, leftovers from personal version
foreach ($profile in $settingsContent.profiles.list) {
if ($profile.commandline -and $profile.commandline.Contains("C:\temp\lab_az.ps1")) {
$profile.commandline = $profile.commandline.Replace("C:\temp\lab_az.ps1", (Join-Path $script:Config.AssetsPath "lab_az.ps1"))
}
}
$settingsContent | ConvertTo-Json -Depth 15 | Out-File (Join-Path $terminalConfigPath "settings.json") -Encoding UTF8
Write-Host " ✓" -ForegroundColor Green
} else {
Write-Host " ✗" -ForegroundColor Red
return $false
}
# see above
$labScriptSource = ".\scripts\lab_az.ps1"
if (Test-Path $labScriptSource) {
Copy-Item $labScriptSource -Destination $script:Config.AssetsPath -Force
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
function Start-WingetBatchInstall {
Write-Host " Installing additional WinGet packages" -NoNewline -ForegroundColor White
$dots = "." * (70 - " Installing additional WinGet packages".Length - 2)
Write-Host $dots -NoNewline -ForegroundColor DarkGray
$packages = @(
"Git.Git",
"7zip.7zip"
)
try {
Write-Host " ✓" -ForegroundColor Green
foreach ($package in $packages) {
$result = winget install --id=$package -e --accept-package-agreements --accept-source-agreements --silent
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne -1978335189) {
Write-StatusLine "Installing package: $package" -Status 'Error' -IsSubStep
} else {
if ($LASTEXITCODE -eq -1978335189) {
Write-StatusLine "Installing package: $package" -Status 'AlreadyInstalled' -IsSubStep -AdditionalInfo "Already installed"
} else {
Write-StatusLine "Installing package: $package" -Status 'Success' -IsSubStep
}
}
}
return $true
}
catch {
Write-Host " ✗" -ForegroundColor Red
return $false
}
}
# installation function junction
function Start-Installation {
param([string]$Mode)
if (-not $Interactive) {
$confirm = Read-Host "Proceed? (y/n)"
if ($confirm -notmatch '^[Yy]') {
return $false
}
}
$steps = @(
{Install-WinGet},
{Install-WindowsTerminal},
{Install-Fonts},
{Set-PSRepository},
{Install-OhMyPosh},
{Install-PowerShellModules},
{Set-PowerShellProfile},
{Set-WindowsTerminalConfig},
{Start-WingetBatchInstall}
)
$successful = 0
$total = $steps.Count
for ($i = 0; $i -lt $steps.Count; $i++) {
$stepNumber = $i + 1
Write-Progress -Activity "Running..." -Status "Step $stepNumber of $total" -PercentComplete (($stepNumber / $total) * 100)
if (& $steps[$i]) {
$successful++
} else {
#
}
}
Write-Progress -Activity "Running..." -Completed
if ($successful -eq $total) {
return $true
} else {
Write-Host ""
Write-Host "Installation completed with $($total - $successful) failures. Check log for details." -ForegroundColor Yellow
return $false
}
}
# Script entry point
try {
Clear-Host
Write-Host "-----------------------------------------------------------------" -ForegroundColor Yellow
Write-Host " github.com/jameswylde/powershell-windowsterminal-profile" -ForegroundColor yellow
Write-Host "-----------------------------------------------------------------" -ForegroundColor Yellow
Write-Host ""
$success = Start-Installation -Mode $Mode
if ($success) {
Write-Host ""
Write-Host "-----------------------------------------------------------------" -ForegroundColor Yellow
Write-Host " C:\Users\$env:Username\AppData\Local\Programs\oh-my-posh\themes\wylde.omp.json" -ForegroundColor Yellow
Write-Host " $env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json" -ForegroundColor Yellow
Write-Host " $PROFILE" -ForegroundColor Yellow
Write-Host "-----------------------------------------------------------------" -ForegroundColor Yellow
Write-Host ""
exit 0
} else {
#Write-Host "`nInstallation completed with some errors" -ForegroundColor Yellow | useless as print above with no - need to readd logging too
exit 1
}
}
catch {
Write-Host ""
Write-Host "Installation failed with unexpected error: " -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
exit 1
}