Repository navigation
Expand file tree
/
Copy pathInstall-Python.ps1
More file actions
804 lines (712 loc) · 31.3 KB
/
Copy pathInstall-Python.ps1
File metadata and controls
804 lines (712 loc) · 31.3 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
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
<#
.SYNOPSIS
Installs or upgrades the latest stable Python 3 release on Windows.
.DESCRIPTION
Discovers existing Python 3 installations via PEP 514 registry keys and standard
install folders, resolves the newest installable Python 3 release from python.org
for the target architecture, verifies the Python Software Foundation Authenticode
signature, installs silently, optionally maintains a fixed-path Python3 directory
junction, and updates User or Machine PATH without mutating unrelated entries.
Exit codes:
0 - Installed or already up to date.
2 - Installed, but persistent PATH was not updated (manual action needed).
5 - Elevation required for -AllUsers in a non-interactive session.
1 (or installer exit code) - Fatal error.
.PARAMETER Series
Pin installation to the newest release of a specific minor series (e.g. 3.13).
.PARAMETER AllUsers
Install system-wide to Program Files and Machine PATH. Prompts for UAC elevation
when run interactively without Administrator privileges.
.PARAMETER Junction
Create or refresh the fixed-path Python3 directory junction pointing to the
installed versioned folder.
.PARAMETER NoJunction
Skip creating or updating the fixed-path Python3 directory junction.
.PARAMETER Unattended
Run non-interactively without prompts or a final pause. Uses the default junction
behavior unless -Junction or -NoJunction is explicitly specified.
.PARAMETER Arch
Target architecture override: amd64 (x64), arm64, or x86 (win32). Defaults to the
native OS architecture.
.PARAMETER NoPause
Skip the final pause when running interactively. Also honored when $env:NOPAUSE is '1'.
.EXAMPLE
.\Install-Python.ps1
.EXAMPLE
.\Install-Python.ps1 3.13 -AllUsers -Unattended
.EXAMPLE
.\Install-Python.ps1 -Arch x86 -NoJunction
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[ValidatePattern('^3\.\d+$')]
[string]$Series,
[Alias('Machine')]
[switch]$AllUsers,
[Alias('StablePath')]
[switch]$Junction,
[Alias('NoStablePath')]
[switch]$NoJunction,
[Alias('Quiet', 'Silent', 'y')]
[switch]$Unattended,
[ValidateSet('amd64', 'x64', 'arm64', 'x86', 'win32')]
[string]$Arch,
[switch]$NoPause
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch {}
$JunctionDefault = $true
$PathHardLimit = 32000
$PathSoftLimit = 2047
$Index = 'https://www.python.org/ftp/python/'
function Write-WarnMessage {
<#
.SYNOPSIS
Writes a yellow warning message to the console.
#>
param([Parameter(Mandatory)][string]$Message)
Write-Host "[WARN] $Message" -ForegroundColor Yellow
}
function Stop-Installer {
<#
.SYNOPSIS
Writes an error message, optionally pauses if interactive, and exits with the given code.
#>
param(
[Parameter(Mandatory)][string]$Message,
[int]$Code = 1,
[bool]$ShouldPause = $false
)
Write-Host "[ERROR] $Message" -ForegroundColor Red
if ($ShouldPause) {
Write-Host ''
Read-Host 'Press Enter to exit' | Out-Null
}
exit $Code
}
function Get-NativePowerShellPath {
<#
.SYNOPSIS
Resolves the current PowerShell executable, preferring native 64-bit Windows PowerShell
when invoked from a 32-bit WoW64 host.
#>
if ($env:PROCESSOR_ARCHITEW6432) {
$sysnative = Join-Path $env:SystemRoot 'Sysnative\WindowsPowerShell\v1.0\powershell.exe'
if (Test-Path -LiteralPath $sysnative) { return $sysnative }
}
try {
return (Get-Process -Id $PID).Path
} catch {
return (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe')
}
}
function Invoke-SelfElevation {
<#
.SYNOPSIS
Relaunches the current script in an elevated PowerShell process with identical parameters.
#>
param(
[Parameter(Mandatory)][string]$ScriptPath,
[Parameter(Mandatory)][hashtable]$BoundParams
)
$argList = New-Object System.Collections.Generic.List[string]
$argList.Add('-NoProfile')
$argList.Add('-ExecutionPolicy')
$argList.Add('Bypass')
$argList.Add('-File')
$argList.Add(('"{0}"' -f $ScriptPath))
foreach ($kv in $BoundParams.GetEnumerator()) {
if ($kv.Value -is [switch]) {
if ($kv.Value.IsPresent) { $argList.Add(('-{0}' -f $kv.Key)) }
} elseif ($null -ne $kv.Value) {
$argList.Add(('-{0}' -f $kv.Key))
$argList.Add(('"{0}"' -f ([string]$kv.Value).Replace('"', '\"')))
}
}
$psExe = Get-NativePowerShellPath
$child = Start-Process -FilePath $psExe -ArgumentList ($argList.ToArray() -join ' ') -Verb RunAs -Wait -PassThru
return $child.ExitCode
}
function Resolve-TargetArchitecture {
<#
.SYNOPSIS
Validates OS version, S Mode restrictions, and target processor architecture.
#>
param(
[string]$TargetSeries,
[string]$ArchOverride,
[bool]$ShouldPause
)
$os = [Environment]::OSVersion.Version
$pinnedOld = $false
if ($TargetSeries) { $pinnedOld = ([int]($TargetSeries.Split('.')[1]) -le 8) }
if ($os.Major -lt 10 -and -not $pinnedOld) {
Stop-Installer -Message 'Current Python releases need Windows 10 or newer. Pin an older series (e.g. 3.8) if you must.' -ShouldPause $ShouldPause
}
if ($os.Major -ge 10 -and $os.Build -lt 17763) {
Write-WarnMessage "Windows build $($os.Build) is old (older than 1809). Recent Python releases may refuse to install or run."
}
$sMode = $false
try {
$sku = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' -Name 'SkuPolicyRequired' -ErrorAction Stop
if ($sku.SkuPolicyRequired -eq 1) { $sMode = $true }
} catch {}
if ($sMode) {
Stop-Installer -Message 'This Windows is in S mode (or a similar locked-down edition) and only runs Store apps. Install Python from the Microsoft Store instead.' -ShouldPause $ShouldPause
}
$osArch = ''
try { $osArch = [string][Runtime.InteropServices.RuntimeInformation]::OSArchitecture } catch {}
if (-not $osArch) {
$osArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
}
$nativeArch = $null
switch -Regex ($osArch) {
'^(x64|amd64)$' { $nativeArch = 'amd64' }
'^arm64$' { $nativeArch = 'arm64' }
'^x86$' { $nativeArch = 'x86' }
'^arm$' { Stop-Installer -Message 'Windows RT / 32-bit ARM is not supported: python.org ships no installer for it.' -ShouldPause $ShouldPause }
default { Stop-Installer -Message "Unsupported processor architecture: $osArch" -ShouldPause $ShouldPause }
}
$resolved = $nativeArch
if ($ArchOverride) {
switch ($ArchOverride.ToLowerInvariant()) {
'amd64' { $resolved = 'amd64' }
'x64' { $resolved = 'amd64' }
'arm64' { $resolved = 'arm64' }
'x86' { $resolved = 'x86' }
'win32' { $resolved = 'x86' }
}
}
if ($resolved -eq 'arm64' -and $nativeArch -ne 'arm64') {
Stop-Installer -Message 'The ARM64 build only runs on ARM64 Windows.' -ShouldPause $ShouldPause
}
if ($resolved -eq 'amd64' -and $nativeArch -eq 'x86') {
Stop-Installer -Message '64-bit Python cannot run on 32-bit Windows.' -ShouldPause $ShouldPause
}
if ($resolved -eq 'amd64' -and $nativeArch -eq 'arm64') {
Write-WarnMessage 'x64 Python on ARM64 runs under emulation (needs Windows 11).'
}
return [pscustomobject]@{
Arch = $resolved
Suffix = @{ amd64 = '-amd64'; arm64 = '-arm64'; x86 = '' }[$resolved]
PlatTag = @{ amd64 = 'win-amd64'; arm64 = 'win-arm64'; x86 = 'win32' }[$resolved]
}
}
function Get-PyInfo {
<#
.SYNOPSIS
Queries a python.exe binary for its major.minor.patch version and sysconfig platform tag.
#>
param([Parameter(Mandatory)][string]$Exe)
try {
$out = & $Exe -c "import sys, sysconfig; print('.'.join(map(str, sys.version_info[:3])), sysconfig.get_platform())" 2>$null
if ($LASTEXITCODE -eq 0 -and "$out" -match '^(\d+\.\d+\.\d+)\s+(\S+)$') {
return [pscustomobject]@{ Version = [version]$Matches[1]; Platform = $Matches[2] }
}
} catch {}
return $null
}
function Test-ReparsePoint {
<#
.SYNOPSIS
Returns true if the path exists and is a filesystem reparse point.
#>
param([Parameter(Mandatory)][string]$Path)
$item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
return [bool]($item -and ($item.Attributes -band [IO.FileAttributes]::ReparsePoint))
}
function Get-InstalledPythons {
<#
.SYNOPSIS
Discovers installed Python 3 interpreters via PEP 514 registry keys and standard install folders.
#>
param([Parameter(Mandatory)][string]$UserRoot)
$found = @{}
$reg = @(
@{ Path = 'HKCU:\Software\Python\PythonCore'; Scope = 'user' },
@{ Path = 'HKLM:\Software\Python\PythonCore'; Scope = 'machine' },
@{ Path = 'HKLM:\Software\WOW6432Node\Python\PythonCore'; Scope = 'machine' }
)
foreach ($r in $reg) {
if (-not (Test-Path $r.Path)) { continue }
foreach ($tag in (Get-ChildItem $r.Path -ErrorAction SilentlyContinue)) {
try {
$ip = Get-ItemProperty -Path (Join-Path $tag.PSPath 'InstallPath') -ErrorAction Stop
$exe = $null
if ($ip.ExecutablePath) { $exe = [string]$ip.ExecutablePath }
elseif ($ip.'(default)') { $exe = Join-Path ([string]$ip.'(default)') 'python.exe' }
if ($exe -and -not $found.ContainsKey($exe)) { $found[$exe] = $r.Scope }
} catch {}
}
}
$dirs = @(
@{ Path = $UserRoot; Scope = 'user' },
@{ Path = $env:ProgramFiles; Scope = 'machine' },
@{ Path = ${env:ProgramFiles(x86)}; Scope = 'machine' }
)
foreach ($d in $dirs) {
if (-not $d.Path) { continue }
Get-ChildItem -Path $d.Path -Directory -Filter 'Python3*' -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
$exe = Join-Path $_.FullName 'python.exe'
if (-not $found.ContainsKey($exe)) { $found[$exe] = $d.Scope }
}
}
foreach ($exe in @($found.Keys)) {
if (-not (Test-Path -LiteralPath $exe)) { continue }
$info = Get-PyInfo -Exe $exe
if ($info -and $info.Version.Major -eq 3) {
[pscustomobject]@{
Path = $exe
Version = $info.Version
Platform = $info.Platform
Scope = $found[$exe]
}
}
}
}
function Get-LatestInstallable {
<#
.SYNOPSIS
Finds the newest stable Python 3 release with a downloadable installer for the target architecture.
#>
param(
[string]$TargetSeries,
[Parameter(Mandatory)][string]$Suffix
)
$versions = @()
try {
$html = (Invoke-WebRequest -Uri $Index -UseBasicParsing -TimeoutSec 30).Content
$versions = @([regex]::Matches($html, 'href="(\d+\.\d+\.\d+)/"') | ForEach-Object { [version]$_.Groups[1].Value })
} catch {
Write-Host " (ftp index unavailable: $($_.Exception.Message))"
}
if ($versions.Count -eq 0) {
try {
$html = (Invoke-WebRequest -Uri 'https://www.python.org/downloads/windows/' -UseBasicParsing -TimeoutSec 30).Content
$versions = @([regex]::Matches($html, 'Python (3\.\d+\.\d+)') | ForEach-Object { [version]$_.Groups[1].Value })
} catch {
Write-Host " (downloads page unavailable: $($_.Exception.Message))"
}
}
$versions = @($versions | Where-Object { $_.Major -eq 3 } | Sort-Object -Unique -Descending)
if ($TargetSeries) {
$versions = @($versions | Where-Object { ('{0}.{1}' -f $_.Major, $_.Minor) -eq $TargetSeries })
}
$tried = 0
foreach ($v in $versions) {
if ($tried++ -ge 25) { break }
$url = "$Index$v/python-$v$Suffix.exe"
try {
$r = Invoke-WebRequest -Uri $url -Method Head -UseBasicParsing -TimeoutSec 30
if ($r.StatusCode -eq 200) { return [pscustomobject]@{ Version = $v; Url = $url } }
} catch {}
}
return $null
}
function Confirm-YesNo {
<#
.SYNOPSIS
Prompts the user with a Yes/No choice dialog in the console.
#>
param(
[Parameter(Mandatory)][string]$Question,
[Parameter(Mandatory)][bool]$Default
)
$yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Yes'
$no = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'No'
$def = if ($Default) { 0 } else { 1 }
return ($Host.UI.PromptForChoice('Stable path', $Question, @($yes, $no), $def) -eq 0)
}
function Set-StableJunction {
<#
.SYNOPSIS
Creates or updates a fixed-path directory junction. Returns created, updated, unchanged, or realdir.
#>
param(
[Parameter(Mandatory)][string]$Link,
[Parameter(Mandatory)][string]$Target
)
$result = 'created'
if (Test-Path -LiteralPath $Link) {
if (-not (Test-ReparsePoint -Path $Link)) { return 'realdir' }
$cur = (Get-Item -LiteralPath $Link -Force).Target
if ($cur -and ([string]@($cur)[0]).TrimEnd('\') -ieq $Target.TrimEnd('\')) { return 'unchanged' }
[IO.Directory]::Delete($Link)
$result = 'updated'
}
[void](New-Item -ItemType Junction -Path $Link -Target $Target)
return $result
}
function Get-PathRegistryKey {
<#
.SYNOPSIS
Opens or creates the User or Machine Environment registry key.
#>
param(
[Parameter(Mandatory)][bool]$Machine,
[Parameter(Mandatory)][bool]$Writable
)
try {
if ($Machine) {
return [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $Writable)
}
if ($Writable) {
return [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
}
return [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
} catch { return $null }
}
function Read-RawPathValue {
<#
.SYNOPSIS
Reads the unexpanded Path value from an Environment registry key.
#>
param($Key)
if ($null -eq $Key) { return '' }
return [string]$Key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
}
function Get-NormalizedPathEntry {
<#
.SYNOPSIS
Expands, trims, and lowercases a PATH entry for case-insensitive comparison.
#>
param([Parameter(Mandatory)][string]$Entry)
return [Environment]::ExpandEnvironmentVariables($Entry.Trim().Trim('"')).TrimEnd('\').ToLowerInvariant()
}
function Backup-SystemPaths {
<#
.SYNOPSIS
Writes a timestamped backup of User and Machine PATH values before registry updates.
#>
param([Parameter(Mandatory)][bool]$Machine)
try {
$baseDir = if ($Machine) { $env:ProgramData } else { $env:LOCALAPPDATA }
$dir = Join-Path $baseDir 'PythonInstaller'
[void](New-Item -ItemType Directory -Force -Path $dir)
$file = Join-Path $dir ('path-backup-{0}.txt' -f (Get-Date -Format 'yyyyMMdd-HHmmss'))
$u = Get-PathRegistryKey -Machine $false -Writable $false
$m = Get-PathRegistryKey -Machine $true -Writable $false
$lines = @('[User Path]', (Read-RawPathValue $u), '', '[Machine Path]', (Read-RawPathValue $m))
if ($u) { $u.Close() }
if ($m) { $m.Close() }
Set-Content -LiteralPath $file -Value $lines -Encoding UTF8
Write-Host " PATH backup: $file"
} catch {
Write-WarnMessage "Could not write a PATH backup: $($_.Exception.Message)"
}
}
function Send-EnvironmentChangeBroadcast {
<#
.SYNOPSIS
Broadcasts WM_SETTINGCHANGE so newly spawned processes pick up updated environment variables.
#>
try {
if (-not ('Win32.NativeMethods' -as [type])) {
Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
}
$result = [UIntPtr]::Zero
[void][Win32.NativeMethods]::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, 'Environment', 0x0002, 5000, [ref]$result)
} catch {}
}
function Update-PersistentPath {
<#
.SYNOPSIS
Prepends Python entries to User or Machine PATH, pruning stale managed Python3 entries
and respecting Windows PATH length ceilings without altering unrelated entries.
Returns updated, unchanged, toolong, or failed.
#>
param(
[Parameter(Mandatory)][bool]$Machine,
[Parameter(Mandatory)][string[]]$Add,
[Parameter(Mandatory)][string]$Base
)
$scopeName = if ($Machine) { 'System' } else { 'User' }
$key = Get-PathRegistryKey -Machine $Machine -Writable $true
$other = Get-PathRegistryKey -Machine (-not $Machine) -Writable $false
if (-not $key) {
Write-WarnMessage "Could not open the $scopeName PATH registry key for writing."
return 'failed'
}
try {
$current = Read-RawPathValue $key
$otherLen = [Environment]::ExpandEnvironmentVariables((Read-RawPathValue $other)).Length
$stale = '^' + [regex]::Escape($Base.TrimEnd('\')) + '\\Python3\d*(\\Scripts)?$'
$seen = @{}
$out = New-Object System.Collections.Generic.List[string]
foreach ($entry in $Add) {
$trimmed = $entry.Trim()
if (-not $trimmed) { continue }
$norm = Get-NormalizedPathEntry -Entry $trimmed
if (-not $seen.ContainsKey($norm)) {
$seen[$norm] = $true
$out.Add($trimmed)
}
}
foreach ($entry in ($current -split ';')) {
if ([string]::IsNullOrWhiteSpace($entry)) { continue }
$trimmed = $entry.Trim()
$norm = Get-NormalizedPathEntry -Entry $trimmed
if ($norm -match $stale) { continue }
if ($seen.ContainsKey($norm)) { continue }
$seen[$norm] = $true
$out.Add($trimmed)
}
$new = $out.ToArray() -join ';'
$total = [Environment]::ExpandEnvironmentVariables($new).Length + 1 + $otherLen
if ($total -gt $PathHardLimit) {
Write-WarnMessage "Combined PATH would be $total characters (safe limit $PathHardLimit). PATH was NOT changed."
return 'toolong'
}
if ($new -ceq $current) {
Write-Host " $scopeName PATH already correct."
return 'unchanged'
}
if ($new.Length -gt $PathSoftLimit) {
Write-WarnMessage "$scopeName PATH is $($new.Length) characters. Some older tools and dialogs cannot handle more than $PathSoftLimit."
}
Backup-SystemPaths -Machine $Machine
$key.SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString)
Send-EnvironmentChangeBroadcast
Write-Host " $scopeName PATH updated ($($new.Length) characters)."
return 'updated'
} finally {
$key.Close()
if ($other) { $other.Close() }
}
}
function Update-SessionPath {
<#
.SYNOPSIS
Prepends the new Python directories to the current PowerShell process PATH without duplicates.
#>
param([Parameter(Mandatory)][string[]]$Add)
$seen = @{}
$out = New-Object System.Collections.Generic.List[string]
foreach ($entry in @($Add + ($env:Path -split ';'))) {
if ([string]::IsNullOrWhiteSpace($entry)) { continue }
$trimmed = $entry.Trim()
$norm = Get-NormalizedPathEntry -Entry $trimmed
if (-not $seen.ContainsKey($norm)) {
$seen[$norm] = $true
$out.Add($trimmed)
}
}
$env:Path = $out.ToArray() -join ';'
}
$interactive = (-not $Unattended) -and [Environment]::UserInteractive -and (-not [Console]::IsInputRedirected)
$shouldPause = $interactive -and (-not $NoPause) -and ($env:NOPAUSE -ne '1')
try {
if ($Junction -and $NoJunction) {
Stop-Installer -Message 'Cannot specify both -Junction and -NoJunction.' -ShouldPause $shouldPause
}
$archInfo = Resolve-TargetArchitecture -TargetSeries $Series -ArchOverride $Arch -ShouldPause $shouldPause
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($AllUsers -and -not $isAdmin) {
if (-not $interactive) {
Stop-Installer -Message 'An all-users install needs an elevated (Administrator) prompt.' -Code 5 -ShouldPause $false
}
if (-not $PSCommandPath) {
Stop-Installer -Message 'Cannot self-elevate an in-memory script. Save Install-Python.ps1 or run from an elevated terminal.' -Code 5 -ShouldPause $shouldPause
}
Write-Host 'An all-users install needs administrator rights. Requesting elevation...'
$elevatedRc = Invoke-SelfElevation -ScriptPath $PSCommandPath -BoundParams $PSBoundParameters
Write-Host 'The installer ran in the elevated window. Open a new terminal to use the updated PATH.'
exit $elevatedRc
}
$userRoot = Join-Path $env:LOCALAPPDATA 'Programs\Python'
$machRoot = if ($archInfo.Arch -eq 'x86' -and ${env:ProgramFiles(x86)}) { ${env:ProgramFiles(x86)} } else { $env:ProgramFiles }
$installBase = if ($AllUsers) { $machRoot } else { $userRoot }
$stable = Join-Path $installBase 'Python3'
Write-Host '=========================================='
Write-Host ' Python Latest Installer'
Write-Host (' Scope: {0} Arch: {1}' -f $(if ($AllUsers) { 'all users' } else { 'current user' }), $archInfo.Arch)
if ($Series) { Write-Host " Pinned to series: $Series" }
Write-Host '=========================================='
Write-Host ''
$installed = @(Get-InstalledPythons -UserRoot $userRoot | Where-Object { $_.Platform -eq $archInfo.PlatTag })
if ($Series) {
$installed = @($installed | Where-Object { ('{0}.{1}' -f $_.Version.Major, $_.Version.Minor) -eq $Series })
}
if ($AllUsers) { $installed = @($installed | Where-Object { $_.Scope -eq 'machine' }) }
$best = $installed | Sort-Object Version -Descending | Select-Object -First 1
if ($best) {
Write-Host 'Found existing Python:'
Write-Host " $($best.Path) (Python $($best.Version), $($best.Scope) install)"
} else {
Write-Host 'No existing Python found.'
}
Write-Host ''
$stableIsRealDir = (Test-Path -LiteralPath $stable) -and (-not (Test-ReparsePoint -Path $stable))
$wantJunction = $JunctionDefault
if ($Junction) {
$wantJunction = $true
} elseif ($NoJunction) {
$wantJunction = $false
} elseif ($interactive -and -not $stableIsRealDir) {
$wantJunction = Confirm-YesNo -Question "Keep a stable folder ($stable) that always points to the newest Python?" -Default $JunctionDefault
Write-Host ''
}
Write-Host 'Checking latest Python 3 release on python.org...'
$latest = Get-LatestInstallable -TargetSeries $Series -Suffix $archInfo.Suffix
$pyExe = $null
if (-not $latest) {
if ($best) {
Write-WarnMessage 'Could not determine the latest version (offline?). Keeping the existing Python.'
$pyExe = $best.Path
} else {
Stop-Installer -Message 'Could not find a downloadable installer on python.org, and no Python is installed.' -ShouldPause $shouldPause
}
} else {
Write-Host "Latest installable version: $($latest.Version)"
Write-Host "Download URL: $($latest.Url)"
Write-Host ''
if ($best -and $best.Version -ge $latest.Version) {
Write-Host 'Python is already up to date.'
$pyExe = $best.Path
} else {
$targetDir = Join-Path $installBase ('Python{0}{1}' -f $latest.Version.Major, $latest.Version.Minor)
if ($best -and $best.Version.Major -eq $latest.Version.Major -and $best.Version.Minor -eq $latest.Version.Minor) {
$bestDir = Split-Path -Parent $best.Path
if ($bestDir.StartsWith($installBase, [StringComparison]::OrdinalIgnoreCase)) { $targetDir = $bestDir }
}
$installer = Join-Path $env:TEMP ('python-{0}{1}.exe' -f $latest.Version, $archInfo.Suffix)
try {
Write-Host "Downloading Python $($latest.Version) installer..."
$ok = $false
for ($i = 1; $i -le 3 -and -not $ok; $i++) {
try {
Invoke-WebRequest -Uri $latest.Url -OutFile $installer -UseBasicParsing
if ((Get-Item -LiteralPath $installer).Length -gt 1MB) { $ok = $true }
else { Write-Host " attempt $i produced a suspiciously small file." }
} catch {
Write-Host " attempt $i failed: $($_.Exception.Message)"
}
if (-not $ok -and $i -lt 3) { Start-Sleep -Seconds 3 }
}
if (-not $ok) { Stop-Installer -Message 'Installer download failed.' -ShouldPause $shouldPause }
$sig = Get-AuthenticodeSignature -FilePath $installer
$subject = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { '' }
if ($subject -notmatch 'Python Software Foundation') {
Stop-Installer -Message "Installer is not signed by the Python Software Foundation (signer: '$subject')." -ShouldPause $shouldPause
}
if ($sig.Status -ne 'Valid') {
Write-WarnMessage "Signature status is '$($sig.Status)' (signer matches PSF). Continuing."
}
$allUsersFlag = [int]$AllUsers.IsPresent
Write-Host ''
Write-Host "Installing Python $($latest.Version) to:"
Write-Host " $targetDir"
$instArgs = @(
'/quiet',
"InstallAllUsers=$allUsersFlag",
"InstallLauncherAllUsers=$allUsersFlag",
'Include_pip=1',
'Include_test=0',
'Include_launcher=1',
'PrependPath=0',
'Shortcuts=0',
"TargetDir=`"$targetDir`""
)
$p = Start-Process -FilePath $installer -ArgumentList $instArgs -Wait -PassThru
if ($p.ExitCode -eq 1638) {
Write-WarnMessage 'The installer reports a conflicting install of this Python version family'
Write-WarnMessage '(possibly the other scope). Uninstall it first, or use the matching scope.'
} elseif ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) {
Stop-Installer -Message "Installer exited with code $($p.ExitCode)." -Code $p.ExitCode -ShouldPause $shouldPause
}
$pyExe = Join-Path $targetDir 'python.exe'
if (-not (Test-Path -LiteralPath $pyExe)) {
Stop-Installer -Message "Install finished but python.exe was not found at: $pyExe" -ShouldPause $shouldPause
}
} finally {
if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction SilentlyContinue }
}
}
}
$pyDir = Split-Path -Parent $pyExe
$pathDir = $pyDir
if ($wantJunction) {
Write-Host ''
if ($pyDir.TrimEnd('\') -ieq $stable.TrimEnd('\')) {
Write-Host "Python already lives at the stable path: $stable"
$pathDir = $stable
} else {
try {
[void](New-Item -ItemType Directory -Force -Path $installBase)
$js = Set-StableJunction -Link $stable -Target $pyDir
if ($js -eq 'realdir') {
Write-WarnMessage "A real folder already exists at $stable (probably from an older install), so a link cannot go there."
Write-WarnMessage 'Uninstall that Python (Settings > Apps) and run this again to switch to the stable link.'
} elseif (Test-Path -LiteralPath (Join-Path $stable 'python.exe')) {
Write-Host "Stable path ($js): $stable -> $pyDir"
$pathDir = $stable
} else {
Write-WarnMessage "The link at $stable does not resolve to a Python. Using the real folder."
}
} catch {
Write-WarnMessage "Could not create the stable-path link: $($_.Exception.Message)"
}
}
}
Write-Host ''
Write-Host 'Ensuring Python is on your PATH...'
$toAdd = @($pathDir, (Join-Path $pathDir 'Scripts'))
if (-not $AllUsers) {
$launcher = Join-Path $userRoot 'Launcher'
if (Test-Path -LiteralPath (Join-Path $launcher 'py.exe')) { $toAdd += $launcher }
}
$pathStatus = Update-PersistentPath -Machine $AllUsers.IsPresent -Add $toAdd -Base $installBase
Update-SessionPath -Add $toAdd
$exitCode = 0
if ($pathStatus -eq 'toolong' -or $pathStatus -eq 'failed') {
Write-WarnMessage 'Add these entries to PATH yourself, or call python.exe by its full path:'
$toAdd | ForEach-Object { Write-Host " $_" }
$exitCode = 2
}
Write-Host ''
Write-Host 'Verifying Python...'
& $pyExe -V
if ($LASTEXITCODE -ne 0) { Stop-Installer -Message 'Python executable exists but failed to run.' -ShouldPause $shouldPause }
Write-Host 'Verifying pip...'
& $pyExe -m pip --version 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host ' pip missing, trying ensurepip...'
try { & $pyExe -m ensurepip --upgrade 2>$null | Out-Null } catch {}
& $pyExe -m pip --version
if ($LASTEXITCODE -ne 0) { Stop-Installer -Message 'pip is not working correctly.' -ShouldPause $shouldPause }
}
$pyLauncher = Get-Command py -ErrorAction SilentlyContinue
if ($pyLauncher) {
& $pyLauncher.Source -3 --version >$null 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host 'Launcher check passed: py -3 works.'
} else {
Write-WarnMessage 'py launcher found but failed to launch Python 3.'
}
} else {
Write-WarnMessage 'py launcher not found in this window. The python.exe path below still works.'
}
$finalPyExe = Join-Path $pathDir 'python.exe'
Write-Host ''
if ($exitCode -eq 2) {
Write-WarnMessage 'Completed with warnings. See the messages above.'
} else {
Write-Host 'Python installation is complete.'
}
Write-Host 'Python:'
Write-Host " $finalPyExe"
Write-Host ''
Write-Host 'Open a NEW terminal for persistent PATH changes to take effect.'
if ($shouldPause) {
Write-Host ''
Read-Host 'Press Enter to exit' | Out-Null
}
exit $exitCode
} catch {
Stop-Installer -Message $_.Exception.Message -ShouldPause $shouldPause
}