-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathinstall.ps1
More file actions
6542 lines (6270 loc) · 366 KB
/
Copy pathinstall.ps1
File metadata and controls
6542 lines (6270 loc) · 366 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
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
# Unsloth Studio Installer for Windows PowerShell
#
# Usage, options and the web one-liner: see "Unsloth Studio (web UI)" in the README
# (https://github.com/unslothai/unsloth#unsloth-studio-web-ui). Not repeated here, because
# AMSI scans this file in full before a line of it runs and nothing reads the header from inside.
#
# The web entry point cannot forward arguments, so it takes options as environment variables set
# beforehand (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a
# local run takes the equivalent flags (--no-torch, --skip-autostart, --python, --local).
#
# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $USERPROFILE\.unsloth\studio
#
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
function Install-UnslothStudio {
$ErrorActionPreference = "Stop"
# The user's PowerShell profile has already run by the time this does, and the documented
# piped web entry point documented in the README has no script file to re-launch
# with -NoProfile, so each way a profile can reach in here is cut individually below.
#
# Off, not Latest: this script predates strict mode, testing environment variables that are
# legitimately unset and reading $script: state only some branches assign. Scoped to here
# and below, so the caller keeps its own.
Set-StrictMode -Off
# A profile that sets 'None' -- the startup-time tweak people copy -- is fatal on PowerShell
# 7, which loads NO modules at startup: Test-Path, Write-Host, Select-Object,
# ConvertFrom-Json, Get-FileHash, Invoke-WebRequest, Expand-Archive, Start-Process and
# Get-Content stop resolving, while 5.1 preloads Utility and Management and survives. First
# of the four, because the proxy handoff below calls ConvertTo-Json from Utility too.
$PSModuleAutoLoadingPreference = 'All'
# Proxy keys are kept rather than dropped: on a locked-down corporate host such an entry may
# be the sole route to python.org and the uv release. IsMatch, not -match, so the filter
# leaves no $Matches behind for the rest of the install.
$_UnslothKeptDefaults = @{}
foreach ($_UnslothDefaultKey in @($PSDefaultParameterValues.Keys)) {
# IgnoreCase: 'invoke-webrequest:proxy' is valid PowerShell and binds the same
# parameter, so a case-sensitive filter drops a working proxy on a technicality.
if ($_UnslothDefaultKey -is [string] -and
[regex]::IsMatch(
$_UnslothDefaultKey,
':Proxy(Credential|UseDefaultCredentials)?$',
[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
$_UnslothKeptDefaults[$_UnslothDefaultKey] = $PSDefaultParameterValues[$_UnslothDefaultKey]
}
}
# One profile entry such as 'Start-Process:WindowStyle' or 'Invoke-WebRequest:TimeoutSec'
# silently rebinds every process launch and download here. Assigning with no scope qualifier
# shadows the caller's table for this scope and below only.
$PSDefaultParameterValues = $_UnslothKeptDefaults
# Windows PowerShell 5.1 redraws the Invoke-WebRequest progress bar on every read, and the
# redraw, not the link, sets the rate: on a windows-latest runner the python.org installer
# (27.8 MB) took 41.34s with the bar on against 0.08s with it off, and the uv archive the
# same. That is the multi-minute "slow download" users report. -UseBasicParsing does NOT
# avoid it and PowerShell 7 never had the cost; only this preference does. Same scoping rule
# as the table above: no qualifier, so the caller's own preference survives a piped web run.
$ProgressPreference = 'SilentlyContinue'
# The kept proxies travel to studio/setup.ps1 (launched -NoProfile by unsloth_cli, and it
# downloads the VC++ runtime and the uv installer) as JSON in _UNSLOTH_PS_PROXY_DEFAULTS,
# since a PowerShell variable does not cross a process boundary. Credentials do not travel:
# a PSCredential does not serialize, and an environment variable is the wrong place for one.
$_UnslothProxyHandoff = @{}
foreach ($_UnslothDefaultKey in @($_UnslothKeptDefaults.Keys)) {
$_UnslothDefaultValue = $_UnslothKeptDefaults[$_UnslothDefaultKey]
# [uri] is the form the parameter actually takes and serializes to its own string.
if ($_UnslothDefaultValue -is [uri]) {
$_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultValue.AbsoluteUri
} elseif ($_UnslothDefaultValue -is [string] -or $_UnslothDefaultValue -is [bool]) {
$_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultValue
} elseif ($_UnslothDefaultValue -is [scriptblock]) {
# A script block is the supported form for a DYNAMIC default, e.g.
# { [uri]$env:CORP_PROXY }, evaluated per call by Invoke-WebRequest. Evaluate here
# and hand over the RESULT: executable code must not cross into the child.
try {
$_UnslothDefaultResolved = & $_UnslothDefaultValue
if ($_UnslothDefaultResolved -is [uri]) {
$_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultResolved.AbsoluteUri
} elseif ($_UnslothDefaultResolved -is [string] -or
$_UnslothDefaultResolved -is [bool]) {
$_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultResolved
}
} catch { }
}
}
# A FUNCTION-local, not $script: or an environment variable: under a piped web run this runs
# in the caller's own session, and the value can carry credentials (http://user:secret@proxy
# is the ordinary corporate form) that must not outlive the install on any of the dozens of
# return paths. Module-qualified serializer, as in the probe: a profile alias or function
# named ConvertTo-Json would otherwise reshape this record or throw out of the prologue.
$UnslothProxyHandoffJson =
if ($_UnslothProxyHandoff.Count -gt 0) {
$_UnslothProxyHandoff | Microsoft.PowerShell.Utility\ConvertTo-Json -Compress
}
else { $null }
# PowerShell 7 only, and $false is its default: a profile that flips it on turns every
# non-zero native exit into a terminating error, which with "Stop" above would throw out of
# the setup handoff instead of reaching Exit-InstallFailure. Harmless on 5.1, where the
# variable does not exist.
$PSNativeCommandUseErrorActionPreference = $false
# Reset per invocation, for the reason at $script:IsIntelXpu further down: under
# a piped web run, $script: is the caller's session scope, so a second run in the same
# console would start on the first run's state. These two are the only ones no later
# statement re-assigns unconditionally.
$script:UvExe = 'uv'
$script:UvInstallDestDir = $null
# Same reason, and this one caches a decision about the machine: a policy added or
# removed between two runs in one console, or a replaced launcher under a hash rule,
# would otherwise be answered from the first run's probe.
$script:ShimLaunchBlockedCache = $null
$script:ShimLaunchBlockedPath = $null
$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq "1")
# Same fix as studio/setup.ps1, for the same reason. This script also calls
# Expand-Archive and Get-ExecutionPolicy, which resolve via PSModulePath.
# The desktop app reaches here as Tauri -> Rust -> powershell.exe
# (studio/src-tauri/src/install.rs), and PowerShell only rewrites
# PSModulePath for a direct pwsh -> powershell.exe hop, so the Rust process
# in between leaves Windows PowerShell 5.1 leading with PowerShell 7's
# module directories and unable to load its own copy of that module.
#
# Not restored afterwards, deliberately. $env: is the process environment,
# so running this script in an interactive console leaves the reordering in
# place for that session. A try/finally would not change that for the case
# it is raised about: the interactive path ends by running Studio in the
# foreground, so the finally would not fire until the user stops the server.
# Narrowing the trigger instead would risk skipping the fix on some chain
# this list does not anticipate, and the cost of that is the install failing
# outright, against a session-lived module precedence change here.
if ($PSVersionTable.PSEdition -ne 'Core' -and $env:SystemRoot) {
$_UnslothSystemModules = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\Modules'
if (Test-Path $_UnslothSystemModules) {
# Prepended: the problem is precedence, not absence.
$_UnslothKept = @(
$env:PSModulePath -split ';' |
Where-Object { $_ -and ($_ -ne $_UnslothSystemModules) }
)
$env:PSModulePath = (@($_UnslothSystemModules) + $_UnslothKept) -join ';'
}
}
# Same UTF-8 invariant as studio/setup.ps1, same ordering constraint: this
# rebuilds [Console]::Out, so it precedes the first write.
$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false
try {
[Console]::OutputEncoding = $_UnslothUtf8NoBom
} catch {
# No console: the setter drops the cached writer before throwing, so
# bind UTF-8 ones explicitly. Same fallback as studio/setup.ps1.
try {
$_UnslothStdout = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardOutput()), $_UnslothUtf8NoBom
$_UnslothStdout.AutoFlush = $true
[Console]::SetOut($_UnslothStdout)
$_UnslothStderr = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardError()), $_UnslothUtf8NoBom
$_UnslothStderr.AutoFlush = $true
[Console]::SetError($_UnslothStderr)
} catch { }
}
$OutputEncoding = $_UnslothUtf8NoBom
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
# Resolved once: it picks the output sink in Write-StudioLine and must not
# change mid-run. Same probe as studio/setup.ps1.
$script:StudioStdoutRedirected = $false
try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }
# Write-Host is written by 5.1's console host with its own writer on the OEM
# code page, not the UTF-8 [Console]::Out rebound above. The desktop app
# spawns this script with CREATE_NO_WINDOW and decodes the pipe as UTF-8
# (from_utf8_lossy, studio/src-tauri/src/install.rs), so the banner emoji,
# the U+2500 rule and every warning arrived as U+FFFD. One sink instead: the
# console handle when redirected, Write-Host when interactive, since it is
# the only one that colorizes. Defined above the first write, for the same
# ordering reason as the encoding block.
function Write-StudioLine {
param([string]$Message = "", [string]$ForegroundColor)
if ($script:StudioStdoutRedirected) {
try { [Console]::Out.WriteLine($Message); [Console]::Out.Flush() } catch {}
return
}
if ($PSBoundParameters.ContainsKey('ForegroundColor')) {
Write-Host $Message -ForegroundColor $ForegroundColor
} else {
Write-Host $Message
}
}
# ── Tauri structured output ──
function Write-TauriLog {
param([string]$Tag, [string]$Message)
if ($TauriMode) {
Write-StudioLine "[TAURI:$Tag] $Message"
}
}
# Mirrors _uv_download_markers in install.sh; only what was opened is closed.
$script:UvDownloadMarkerMinBytes = 52428800
if ($env:UNSLOTH_DL_MARKER_MIN_BYTES -match '^\d+$') {
$script:UvDownloadMarkerMinBytes = [long]$env:UNSLOTH_DL_MARKER_MIN_BYTES
}
$script:UvAnnouncedDownloads = @{}
function Write-UvDownloadMarker {
param([string]$Line)
if (-not $TauriMode) { return }
if ($Line -match '(?:^|\s)Downloading (\S+) \(([0-9.]+)(KiB|MiB|GiB)\)\s*$') {
$unit = @{ KiB = 1024L; MiB = 1048576L; GiB = 1073741824L }[$Matches[3]]
if ([double]$Matches[2] * $unit -ge $script:UvDownloadMarkerMinBytes) {
$script:UvAnnouncedDownloads[$Matches[1]] = $true
Write-TauriLog "DL" "$($Matches[1]) $($Matches[2])$($Matches[3])"
}
} elseif ($Line -match '(?:^|\s)Downloaded (\S+)\s*$') {
# ContainsKey, not Remove's return: Hashtable.Remove is void.
if ($script:UvAnnouncedDownloads.ContainsKey($Matches[1])) {
$script:UvAnnouncedDownloads.Remove($Matches[1])
Write-TauriLog "DL_DONE" $Matches[1]
}
}
}
function Clear-TauriInstallError {
param([string]$Message)
if ($TauriMode) {
Write-TauriLog "ERROR_CLEAR" $Message
[Console]::Error.WriteLine("[TAURI:ERROR_CLEAR] $Message")
}
}
function Format-TauriDiagBool {
param([bool]$Value)
if ($Value) { return "true" }
return "false"
}
function Get-TauriDiagArch {
$arch = [string]$env:PROCESSOR_ARCHITECTURE
if ([string]::IsNullOrWhiteSpace($arch)) {
try { $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { $arch = "unknown" }
}
$arch = $arch.ToLowerInvariant()
switch ($arch) {
"amd64" { return "x86_64" }
"x64" { return "x86_64" }
"arm64" { return "arm64" }
"x86" { return "x86" }
default { return ($arch -replace '[^a-z0-9_.-]', '_') }
}
}
# Machine arch; Get-TauriDiagArch above reports the process. An emulated x64 shell on
# ARM64 reports AMD64, but PROCESSOR_ARCHITEW6432 is ARM64 in exactly that case.
function Get-HostMachineArch {
$osArch = ""
try { $osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { $osArch = "" }
$signals = @([string]$env:PROCESSOR_ARCHITEW6432, [string]$env:PROCESSOR_ARCHITECTURE, $osArch)
foreach ($s in $signals) {
if ($s.ToLowerInvariant() -eq "arm64") { return "arm64" }
}
foreach ($s in $signals) {
if ([string]::IsNullOrWhiteSpace($s)) { continue }
switch ($s.ToLowerInvariant()) {
"amd64" { return "x86_64" }
"x64" { return "x86_64" }
"x86" { return "x86" }
}
}
return "unknown"
}
function Get-TauriTorchIndexFamily {
param([string]$TorchIndexUrl)
if ($SkipTorch) { return "none" }
if ([string]::IsNullOrWhiteSpace($TorchIndexUrl)) { return "none" }
# Drop query/fragment first so a token-authenticated pin classifies by family.
$leaf = (($TorchIndexUrl -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1].ToLowerInvariant()
if (@("cpu", "xpu", "cu118", "cu124", "cu126", "cu128", "cu130") -contains $leaf) { return $leaf }
if ($leaf -match '^rocm[0-9]+\.[0-9]+$') { return $leaf }
return "auto"
}
function Get-TauriGpuBranch {
param([string]$TorchIndexFamily)
if ($SkipTorch) { return "no_torch" }
# Require a digit after "cu" so /current or /custom isn't branded CUDA (parity ^cu[0-9]).
if ($TorchIndexFamily -match '^cu[0-9]') { return "cuda" }
if ($TorchIndexFamily -like "rocm*") { return "rocm" }
if ($TorchIndexFamily -eq "xpu") { return "xpu" }
if ($TorchIndexFamily -eq "cpu") { return "cpu" }
return "unknown"
}
function Write-TauriDiag {
param(
[string]$GpuBranch = "unknown",
[string]$TorchIndexFamily = "none",
[string]$PythonVersionForDiag = $PythonVersion
)
if ([string]::IsNullOrWhiteSpace($PythonVersionForDiag)) { $PythonVersionForDiag = "unknown" }
Write-TauriLog "DIAG" "diag_schema=1 platform=windows arch=$(Get-TauriDiagArch) python_version=$($PythonVersionForDiag.ToLowerInvariant()) skip_torch=$(Format-TauriDiagBool $SkipTorch) mac_intel=false gpu_branch=$GpuBranch torch_index_family=$TorchIndexFamily"
}
function Exit-InstallFailure {
param(
[Parameter(Mandatory = $true)][string]$Message,
[int]$Code = 1
)
if ($Code -eq 0) { $Code = 1 }
Write-TauriLog "ERROR_DEFAULT" $Message
if (Get-Command Restore-StudioVenvRollback -CommandType Function -ErrorAction SilentlyContinue) {
Restore-StudioVenvRollback
}
# Most failures return before the lock try/finally, and under `irm | iex`
# these variables are the caller's own. Defined later, so probed like above.
if (Get-Command Restore-StudioTempEnvironment -CommandType Function -ErrorAction SilentlyContinue) {
Restore-StudioTempEnvironment
}
if ($TauriMode) {
exit $Code
}
throw $Message
}
# ── Usable temporary storage ──
# Windows picks the temp directory from TMP, then TEMP, then the profile, and
# never checks it exists or is writable. The desktop app passes on whatever it
# inherited (studio/src-tauri/src/install.rs sets neither); one report had it at
# C:\Windows\TEMP, where the source Add-Type had just written was gone by the
# time csc.exe opened it (issue #9140). The Python, uv and VC++ downloads stage
# through it too. Probe it once and, if it cannot hold a file, point BOTH
# variables at a directory we own: every child process and every
# [System.IO.Path]::GetTempPath() call reads the process environment block.
function Test-StudioDirectoryUsable {
param(
[string]$Path,
# Only for a directory this installer OWNS. Probing the host's own
# inherited TMP/TEMP must not bring it into existence: -Force creates
# the whole parent chain, so a stale or mistyped TMP would have the
# installer silently materialize a tree at a path nobody chose, and
# then trust it. Absent means unusable, which is what the private
# fallback is for.
[switch]$CreateIfMissing
)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
try {
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
if (-not $CreateIfMissing) { return $false }
New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null
}
# Anything an earlier run could not delete. Bounded self-healing: the
# probe below cannot clean up after itself when deletion is what
# failed, so each such run used to leave one more file behind forever.
try {
$cutoff = (Get-Date).AddDays(-1)
foreach ($old in @(Get-ChildItem -LiteralPath $Path -File -Filter "unsloth-probe-*.tmp" -ErrorAction Stop)) {
# Shape, not prefix. This runs in the HOST's temp directory,
# where a name that merely starts the same way belongs to
# somebody else; the probe below only ever writes eight hex
# characters, so anything else is not ours to delete.
if ($old.Name -notmatch '^unsloth-probe-[0-9a-f]{8}\.tmp$') { continue }
if ($old.LastWriteTime -lt $cutoff) {
Remove-Item -LiteralPath $old.FullName -Force -ErrorAction SilentlyContinue
}
}
} catch {}
# Write, read back, delete -- not Test-Path: the failures that matter
# (write without read, a scanner deleting the file) pass an existence check.
$probe = Join-Path $Path ("unsloth-probe-" + [guid]::NewGuid().ToString('N').Substring(0, 8) + ".tmp")
[System.IO.File]::WriteAllText($probe, "unsloth")
$readBack = [System.IO.File]::ReadAllText($probe)
# Deleting has to work too, and be VERIFIED. csc.exe writes its source
# and its output into this directory and then cleans up, so one that
# accepts a file and will not give it back is the shape that produced
# #9140; a suppressed Remove-Item said nothing either way. Retried a
# couple of times first, because a scanner holding the file for a
# moment is not the same as a directory that denies deletion, and only
# the second should cost a healthy host its own temp.
$probeGone = $false
foreach ($attempt in 1..3) {
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
if (-not [System.IO.File]::Exists($probe)) { $probeGone = $true; break }
Start-Sleep -Milliseconds 100
}
if (-not $probeGone) { return $false }
return ($readBack -eq "unsloth")
} catch {
return $false
}
}
function Remove-StudioStalePrivateTempDirectories {
param([Parameter(Mandatory = $true)][string]$Root)
# These outlive the install (an autostarted Studio inherits one as its own
# %TEMP%), so bound the pile by age instead of deleting one still in use.
try {
$cutoff = (Get-Date).AddDays(-1)
foreach ($stale in @(Get-ChildItem -LiteralPath $Root -Directory -Filter "ust-*" -ErrorAction Stop)) {
# SHAPE, not prefix. The delete below is recursive and this is the
# only ownership test there is, so it has to name a directory the
# allocator could actually have made: "ust-" + $PID + "-" + 8 hex.
# A prefix match takes "ust-legacy" or "ust-user-cache" too, and
# since neither has a parseable PID the liveness check is skipped
# for exactly the names least likely to be ours. scripts/uninstall.ps1
# already requires this shape; the two had drifted apart.
if ($stale.Name -notmatch '^ust-[0-9]+-[0-9a-f]{8}$') { continue }
if ($stale.LastWriteTime -ge $cutoff) { continue }
# Before any owner logic, because the allocator never makes a link:
# anything here that IS one is not ours, reading owner.pid out of it
# would read through it, and unlinking is safe whatever owns the
# target. Not Remove-Item: on 5.1 without -Recurse it throws a
# NullReferenceException on a junction that -ErrorAction
# SilentlyContinue does not suppress (measured on windows-latest), and
# -Recurse has walked THROUGH the link on some 5.1 builds.
# Directory.Delete with recursive:$false cannot follow it.
if ($stale.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
try { [System.IO.Directory]::Delete($stale.FullName, $false) } catch {}
continue
}
# Age alone is not proof it is unused, and this sweep runs before the
# runtime mutex, so it could delete a live process's %TEMP%. owner.pid
# names the process that INHERITED this directory (the autostarted
# Studio, which outlives the installer); the PID in the name is only
# the installer's and is already gone. If the owner is alive, leave it.
# PID reuse only ever costs a directory its cleanup.
$ownerPid = 0
$ownerFile = Join-Path $stale.FullName "owner.pid"
$recorded = $null
try {
if ([System.IO.File]::Exists($ownerFile)) {
$recorded = [System.IO.File]::ReadAllText($ownerFile).Trim()
}
} catch { $recorded = $null }
if (-not [string]::IsNullOrWhiteSpace($recorded)) {
$null = [int]::TryParse($recorded, [ref]$ownerPid)
}
# Whether the owner was RECORDED, or only guessed from the name.
# The name carries the installer's PID, and an installer that was
# killed between Start-Process and the owner.pid write leaves a dead
# PID in the name while the Studio it started is very much alive on
# that directory as its own %TEMP%. Guessing therefore proves much
# less than reading, and the two are not treated alike below.
$ownerRecorded = ($ownerPid -gt 0)
if ($ownerPid -le 0) {
$null = [int]::TryParse(($stale.Name -split '-')[1], [ref]$ownerPid)
}
# No recorded owner: unknown, not abandoned. Still collected, so the
# pile stays bounded, but only once it has gone a whole week without
# a single entry being created in it, which a Studio actually using
# it as %TEMP% would not manage.
if (-not $ownerRecorded -and $stale.LastWriteTime -ge (Get-Date).AddDays(-7)) {
continue
}
if ($ownerPid -gt 0) {
$ownerLives = $true
try {
$null = Get-Process -Id $ownerPid -ErrorAction Stop
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
# The only answer that means "abandoned"; any other failure
# says nothing about the owner, so keep the directory.
$ownerLives = $false
} catch {
$ownerLives = $true
}
if ($ownerLives) { continue }
}
Remove-Item -LiteralPath $stale.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
} catch {}
}
function Set-StudioPrivateTempOwner {
param([Parameter(Mandatory = $true)][int]$OwnerProcessId)
# Only meaningful if this run redirected the temp; otherwise it is the host's.
if ($null -eq $script:StudioTempOverride) { return }
# Only a directory this run created. The other override shape just pins the
# absolute spelling of the host's own temp, and dropping a file in there
# would be litter in somebody else's directory.
if (-not $script:StudioTempOverride.Owned) { return }
$owned = $script:StudioTempOverride.Path
if ([string]::IsNullOrWhiteSpace($owned)) { return }
try {
[System.IO.File]::WriteAllText((Join-Path $owned "owner.pid"), [string]$OwnerProcessId)
} catch {}
}
function Get-StudioPrivateTempRoots {
# Only under paths scripts/uninstall.ps1 already reclaims (LOCALAPPDATA\
# "Unsloth Studio", ~\.unsloth\.cache): anywhere else would survive an
# uninstall, and a leftover directly under ~\.unsloth would be worse, since
# that is removed only when empty.
$roots = @()
if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
$roots += (Join-Path $env:LOCALAPPDATA "Unsloth Studio\temp")
}
try {
$localAppData = [Environment]::GetFolderPath("LocalApplicationData")
if (-not [string]::IsNullOrWhiteSpace($localAppData)) {
$roots += (Join-Path $localAppData "Unsloth Studio\temp")
}
} catch {}
if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
$roots += (Join-Path $env:USERPROFILE ".unsloth\.cache\temp")
}
return $roots
}
function New-StudioPrivateTempDirectory {
foreach ($root in @(Get-StudioPrivateTempRoots)) {
# Short leaf: the .NET Framework compiler 5.1 shells out to is still
# bound by the legacy path limit.
$leaf = "ust-" + $PID + "-" + [guid]::NewGuid().ToString('N').Substring(0, 8)
$candidate = Join-Path $root $leaf
# Which of these did not exist BEFORE the probe touched anything. Only
# those may be unwound below: a pre-provisioned "Unsloth Studio\temp"
# with custom ACLs, or an empty junction pointing somewhere else, is
# configuration this installer did not create and must not remove
# merely for being empty and correctly named.
$preAbsent = @{}
$walk = $candidate
for ($seen = 0; $seen -lt 4; $seen++) {
if ([string]::IsNullOrEmpty($walk)) { break }
$preAbsent[$walk] = (-not (Test-Path -LiteralPath $walk))
$walk = [System.IO.Path]::GetDirectoryName($walk)
}
if (Test-StudioDirectoryUsable -Path $candidate -CreateIfMissing) {
Remove-StudioStalePrivateTempDirectories -Root $root
return $candidate
}
# The probe creates the candidate before it tests it, and -Force builds
# the whole chain, so a root that fails leaves "Unsloth Studio\temp\ust-x"
# behind; on a host where every root fails that is a data directory tree
# conjured by an install that then gave up. Walk back up, but only through
# the directories this path is made of and only while each one is EMPTY,
# so a tree that already held something is never touched and neither is
# ~\.unsloth itself, which is shared and is not ours to remove.
$ours = @("temp", "Unsloth Studio", ".cache")
$unwind = $candidate
for ($depth = 0; $depth -lt 4; $depth++) {
try {
if (-not $preAbsent[$unwind]) { break }
if (-not (Test-Path -LiteralPath $unwind -PathType Container)) { break }
$item = Get-Item -LiteralPath $unwind -Force -ErrorAction Stop
# A relocation junction is somebody's configuration even when the
# probe created it, and unlinking it is not "taking back what we
# made". Leave it and stop.
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { break }
if (@(Get-ChildItem -LiteralPath $unwind -Force -ErrorAction Stop).Count -gt 0) { break }
[System.IO.Directory]::Delete($unwind, $false)
} catch { break }
$unwind = [System.IO.Path]::GetDirectoryName($unwind)
if ([string]::IsNullOrEmpty($unwind)) { break }
if ($ours -notcontains [System.IO.Path]::GetFileName($unwind)) { break }
}
}
return $null
}
$script:StudioTempOverride = $null
$script:StudioTempChecked = $false
function Initialize-StudioTempEnvironment {
if ($script:StudioTempChecked) { return }
$script:StudioTempChecked = $true
# TMP wins over TEMP, so only fall through when TMP is unset. IsNullOrEmpty,
# not IsNullOrWhiteSpace: GetTempPath takes the first of TMP/TEMP that is
# merely non-empty, so a whitespace-only TMP is what Windows and every child
# will use, and treating it as unset would probe a healthy TEMP and change
# nothing.
$inherited = if (-not [string]::IsNullOrEmpty($env:TMP)) { $env:TMP } else { $env:TEMP }
# Resolve BEFORE probing, not after. Test-Path is relative to PowerShell's
# location while the .NET file APIs are relative to the process working
# directory, and Set-Location moves only the first, so probing a relative
# value can check one directory and write to another.
# Whitespace-only is left exactly as it is, so the probe below rejects it.
# Resolving it first would turn " " or a tab into the working directory
# plus that name, which is creatable on some filesystems, and the installer
# would manufacture a junk directory and then trust it as the host's temp.
$absolute = $inherited
if (-not [string]::IsNullOrWhiteSpace($inherited)) {
try { $absolute = [System.IO.Path]::GetFullPath($inherited) } catch { $absolute = $inherited }
}
if (Test-StudioDirectoryUsable -Path $absolute) {
# A host whose temp was fixed since the last run never allocates another
# private directory, and the allocator is the only thing that sweeps.
# Without this, whatever an earlier degraded run left behind ages in
# place until an uninstall. Each root that does not exist is a no-op.
foreach ($root in @(Get-StudioPrivateTempRoots)) {
Remove-StudioStalePrivateTempDirectories -Root $root
}
# Pin what was probed. A relative value (temp, or the drive-relative
# C:temp) is resolved by whoever reads it, and the install relocates
# out of a Windows system directory further down, so the same value
# could later name somewhere else, or nowhere. An already-absolute
# value normalizes to itself and is left alone.
if (-not [string]::Equals($absolute, $inherited, [System.StringComparison]::Ordinal)) {
$script:StudioTempOverride = [pscustomobject]@{
TmpSet = ($null -ne $env:TMP)
TmpValue = $env:TMP
TempSet = ($null -ne $env:TEMP)
TempValue = $env:TEMP
Path = $absolute
Owned = $false
}
$env:TMP = $absolute
$env:TEMP = $absolute
}
return
}
$private = New-StudioPrivateTempDirectory
if (-not $private) {
Write-StudioLine "[WARN] No writable temporary directory was found; downloads may fail." -ForegroundColor Yellow
return
}
# Absent is not empty: restoring an absent variable as "" would change how
# every later child resolves its own temp directory.
$script:StudioTempOverride = [pscustomobject]@{
TmpSet = ($null -ne $env:TMP)
TmpValue = $env:TMP
TempSet = ($null -ne $env:TEMP)
TempValue = $env:TEMP
Path = $private
Owned = $true
}
$env:TMP = $private
$env:TEMP = $private
Write-StudioLine "[WARN] The inherited temporary directory is not usable; this install will use its own." -ForegroundColor Yellow
}
function Restore-StudioTempEnvironment {
$override = $script:StudioTempOverride
if ($null -eq $override) { return }
$script:StudioTempOverride = $null
if ($override.TmpSet) { $env:TMP = $override.TmpValue }
else { Remove-Item Env:\TMP -ErrorAction SilentlyContinue }
if ($override.TempSet) { $env:TEMP = $override.TempValue }
else { Remove-Item Env:\TEMP -ErrorAction SilentlyContinue }
# The directory stays: an autostarted Studio inherited it as its own %TEMP%,
# and the host's real one is broken. The next run sweeps the old ones.
}
# ── Parse flags ──
$StudioLocalInstall = $false
$PackageName = "unsloth"
$RepoRoot = ""
$TauriMode = $false
$SkipTorch = $false
$SkipAutostart = $false
$ShortcutsOnly = $false
$WithLlamaCppDir = ""
$argList = $args
for ($i = 0; $i -lt $argList.Count; $i++) {
switch ($argList[$i]) {
"--local" { $StudioLocalInstall = $true }
"--tauri" { $TauriMode = $true }
"--no-torch" { $SkipTorch = $true }
"--verbose" { $script:UnslothVerbose = $true }
"-v" { $script:UnslothVerbose = $true }
"--shortcuts-only" { $ShortcutsOnly = $true }
"--package" {
$i++
if ($i -ge $argList.Count) {
Write-StudioLine "[ERROR] --package requires an argument." -ForegroundColor Red
return (Exit-InstallFailure "--package requires an argument.")
}
$PackageName = $argList[$i]
}
"--with-llama-cpp-dir" {
$i++
if ($i -ge $argList.Count) {
Write-StudioLine "[ERROR] --with-llama-cpp-dir requires a path argument." -ForegroundColor Red
return (Exit-InstallFailure "--with-llama-cpp-dir requires a path argument.")
}
$WithLlamaCppDir = $argList[$i]
}
}
}
# Env-var equivalent for web installs; an explicit flag still wins.
if ($env:UNSLOTH_NO_TORCH -in @('1', 'true', 'yes', 'on')) { $SkipTorch = $true }
if ($env:UNSLOTH_SKIP_AUTOSTART -in @('1', 'true', 'yes', 'on')) { $SkipAutostart = $true }
# Propagate to child processes so they also respect verbose mode.
# Process-scoped -- does not persist.
if ($script:UnslothVerbose) {
$env:UNSLOTH_VERBOSE = '1'
}
if ($StudioLocalInstall) {
$RepoRoot = (Resolve-Path (Split-Path -Parent $PSCommandPath)).Path
if (-not (Test-Path (Join-Path $RepoRoot "pyproject.toml"))) {
Write-StudioLine "[ERROR] --local must be run from the unsloth repo root (pyproject.toml not found at $RepoRoot)" -ForegroundColor Red
return (Exit-InstallFailure "--local must be run from the unsloth repo root")
}
}
# Validate --package to prevent injection into shell/Python commands
if ($PackageName -notmatch '^[a-zA-Z0-9][a-zA-Z0-9._-]*$') {
Write-StudioLine "[ERROR] --package name contains invalid characters (allowed: a-z A-Z 0-9 . _ -)" -ForegroundColor Red
return (Exit-InstallFailure "--package name contains invalid characters")
}
# UNSLOTH_PYTHON pins the version (mirrors install.sh --python); default 3.13.
$PythonVersion = if ($env:UNSLOTH_PYTHON) { $env:UNSLOTH_PYTHON } else { "3.13" }
# python.org fallback patch, used only when winget is unavailable/broken AND
# the live python.org listing can't be fetched. The installer URL scheme is
# stable so an older patch still installs. Bump alongside $PythonVersion.
$PythonFallbackFullVersion = "3.13.13"
# Patch releases the stack cannot run; mirrors PYTHON_SKIP in install.sh.
# Windows resolves an installed interpreter and hands uv its path rather
# than a version, so uv never picks one of these -- but the machine may
# already have it, and $PythonFallbackFullVersion above is what replaces it.
$PythonSkip = @("3.13.8")
# The entry above is skipped for one reason: it cannot `import torch`. A
# -NoTorch install never imports it, so refusing the interpreter would send a
# locked-down GGUF-only machine into winget/python.org recovery it may not be
# able to complete, over a package it will not install.
if ($SkipTorch) { $PythonSkip = @() }
# Resolve install destinations. Priority: UNSLOTH_STUDIO_HOME, then
# STUDIO_HOME alias, then USERPROFILE-redirect, then default.
# Reject whitespace-only values so " " is treated as unset (matches the
# Python resolvers' .strip()), preventing install/runtime layout drift.
$envOverrideVar = $null
$envOverride = $null
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) {
$envOverrideVar = "UNSLOTH_STUDIO_HOME"
$envOverride = $env:UNSLOTH_STUDIO_HOME.Trim()
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$envOverrideVar = "STUDIO_HOME"
$envOverride = $env:STUDIO_HOME.Trim()
}
$defaultProfile = $null
try { $defaultProfile = [Environment]::GetFolderPath("UserProfile") } catch {}
$tauriProfile = if ($defaultProfile) { $defaultProfile } else { $env:USERPROFILE }
# GetFinalPathNameByHandleW is the only exact answer: it follows junctions,
# symlinks and SUBST drives, expands 8.3 aliases and reports the on-disk
# spelling, none of which GetFullPath does. It costs a C# compile, and 5.1 (the
# interpreter the desktop app spawns) compiles by writing the source to %TEMP%
# and running csc.exe. When that directory is unusable, or a scanner eats the
# source, Add-Type throws CS2001, which used to abort a first launch as "Could
# not create the Studio install lock" (issue #9140). Try once, retry with a
# %TEMP% we own, cache the answer (callers resolve dozens of paths), then let
# Get-StudioLexicalPath carry the run.
$script:StudioFinalPathNativeState = $null
# Reset with the rest: under `irm | iex` these are the caller's own.
$script:StudioNativeResolveWarned = $false
$script:StudioFinalPathWarned = $false
function Write-StudioFinalPathDegraded {
param([string]$Reason)
if ($script:StudioFinalPathWarned) { return }
$script:StudioFinalPathWarned = $true
Write-StudioLine "[WARN] Could not load the native path resolver ($Reason)." -ForegroundColor Yellow
Write-StudioLine " Continuing with the PowerShell resolver; installation is unaffected." -ForegroundColor Yellow
}
function Initialize-StudioFinalPathNativeType {
if ("UnslothStudioFinalPathV2" -as [type]) {
$script:StudioFinalPathNativeState = $true
return $true
}
if ($null -ne $script:StudioFinalPathNativeState) { return $script:StudioFinalPathNativeState }
# Constrained Language Mode forbids Add-Type, so compiling would only produce
# a second, less honest error.
$languageMode = "FullLanguage"
try { $languageMode = [string]$ExecutionContext.SessionState.LanguageMode } catch {}
if ($languageMode -ne "FullLanguage") {
$script:StudioFinalPathNativeState = $false
Write-StudioFinalPathDegraded -Reason "PowerShell is in $languageMode"
return $false
}
Initialize-StudioTempEnvironment
$source = @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
public static class UnslothStudioFinalPathV2
{
private const uint FileShareRead = 0x00000001;
private const uint FileShareWrite = 0x00000002;
private const uint FileShareDelete = 0x00000004;
private const uint OpenExisting = 3;
private const uint FileFlagBackupSemantics = 0x02000000;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(
string fileName,
uint desiredAccess,
uint shareMode,
IntPtr securityAttributes,
uint creationDisposition,
uint flagsAndAttributes,
IntPtr templateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetFinalPathNameByHandleW(
SafeFileHandle file,
StringBuilder path,
uint pathLength,
uint flags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(
uint desiredAccess,
bool inheritHandle,
int processId);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool QueryFullProcessImageNameW(
IntPtr process,
uint flags,
StringBuilder path,
ref uint pathLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
public static string Resolve(string path)
{
using (SafeFileHandle handle = CreateFileW(
path,
0,
FileShareRead | FileShareWrite | FileShareDelete,
IntPtr.Zero,
OpenExisting,
FileFlagBackupSemantics,
IntPtr.Zero))
{
if (handle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
StringBuilder buffer = new StringBuilder(512);
uint length = GetFinalPathNameByHandleW(
handle, buffer, (uint)buffer.Capacity, 0);
if (length == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
if (length >= buffer.Capacity)
{
buffer = new StringBuilder((int)length + 1);
length = GetFinalPathNameByHandleW(
handle, buffer, (uint)buffer.Capacity, 0);
if (length == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (length >= buffer.Capacity)
throw new InvalidOperationException("Final path exceeded the allocated buffer");
return buffer.ToString();
}
}
public static string GetProcessImagePath(int processId)
{
const uint ProcessQueryLimitedInformation = 0x1000;
IntPtr process = OpenProcess(ProcessQueryLimitedInformation, false, processId);
if (process == IntPtr.Zero)
{
return null;
}
try
{
StringBuilder path = new StringBuilder(32768);
uint pathLength = (uint)path.Capacity;
return QueryFullProcessImageNameW(process, 0, path, ref pathLength)
? path.ToString()
: null;
}
finally
{
CloseHandle(process);
}
}
}
'@
$firstError = $null
try {
Add-Type -TypeDefinition $source -ErrorAction Stop
} catch {
$firstError = $_.Exception.Message
}
# A compile that reports failure can still have loaded the type, and the same
# name cannot be defined twice in one session.
if ("UnslothStudioFinalPathV2" -as [type]) {
$script:StudioFinalPathNativeState = $true
return $true
}
$private = New-StudioPrivateTempDirectory
if ($private) {
$hadTmp = ($null -ne $env:TMP)
$previousTmp = $env:TMP
$hadTemp = ($null -ne $env:TEMP)
$previousTemp = $env:TEMP
try {
# Both, because GetTempPath reads TMP first.
$env:TMP = $private
$env:TEMP = $private
try { Add-Type -TypeDefinition $source -ErrorAction Stop } catch {}
} finally {
if ($hadTmp) { $env:TMP = $previousTmp } else { Remove-Item Env:\TMP -ErrorAction SilentlyContinue }
if ($hadTemp) { $env:TEMP = $previousTemp } else { Remove-Item Env:\TEMP -ErrorAction SilentlyContinue }
# Only now: deleting while csc.exe still holds it is the race being
# worked around.
Remove-Item -LiteralPath $private -Recurse -Force -ErrorAction SilentlyContinue
}
}
if ("UnslothStudioFinalPathV2" -as [type]) {
$script:StudioFinalPathNativeState = $true
return $true
}
$script:StudioFinalPathNativeState = $false
# First line of the compiler output, not the whole C# dump it echoes after.
$reason = if ($firstError) { ($firstError -split "`r?`n")[0].Trim() } else { "compilation failed" }
Write-StudioFinalPathDegraded -Reason $reason
return $false
}
function Resolve-StudioLinkTarget {
param([Parameter(Mandatory = $true)][string]$Path)
$item = $null
try { $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop } catch { return $null }
$target = $null
# PowerShell 7 walks the whole chain; 5.1 exposes only the raw reparse target,
# relative for a relative symlink and still carrying a junction's NT prefix.
if ($item.PSObject.Methods.Name -contains 'ResolveLinkTarget') {
try {
$final = $item.ResolveLinkTarget($true)
if ($final) { $target = [string]$final.FullName }
} catch { $target = $null }
}
if ([string]::IsNullOrWhiteSpace($target)) {
$raw = $null
try { $raw = $item.Target } catch { $raw = $null }
# 5.1 hands this back as a COLLECTION, not a string, and not always an
# [array], so unwrap anything that is not already a string.
if ($null -ne $raw -and $raw -isnot [string]) {
$raw = @($raw) | Select-Object -First 1
}
if (-not [string]::IsNullOrWhiteSpace($raw)) { $target = [string]$raw }
}
if ([string]::IsNullOrWhiteSpace($target)) { return $null }
if ($target.StartsWith('\??\')) {
$target = $target.Substring(4)
# \??\UNC\server\share is the device spelling of \\server\share. Left as
# "UNC\server\share" it reads as RELATIVE and gets combined with the
# link's local parent, inventing a path; a wrong identity is a wrong mutex.
if ($target.StartsWith('UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
$target = '\\' + $target.Substring(4)
} elseif ($target.StartsWith('Volume{', [System.StringComparison]::OrdinalIgnoreCase)) {
# A mounted folder reports \??\Volume{GUID}\..., the same trap:
# "Volume{...}\..." is not rooted either. \\?\ is the extended-length
# spelling of that device path, so it keeps naming the volume.
$target = '\\?\' + $target
}
}
# "\real" is rooted as far as IsPathRooted is concerned but names no drive,
# so GetFullPath would resolve it against the PROCESS current drive. Windows
# resolves a drive-less target on the LINK's own volume, so anchor it there.
if ($target.Length -ge 1 -and ($target[0] -eq '\' -or $target[0] -eq '/') -and
-not ($target.Length -ge 2 -and ($target[1] -eq '\' -or $target[1] -eq '/'))) {
$linkRoot = $null
try { $linkRoot = [System.IO.Path]::GetPathRoot([System.IO.Path]::GetFullPath($Path)) } catch { $linkRoot = $null }
# Empty for a volume-GUID spelling; leaving the target alone beats guessing.
if (-not [string]::IsNullOrEmpty($linkRoot)) {
try { $target = [System.IO.Path]::Combine($linkRoot, $target.TrimStart('\', '/')) } catch {}
}
}
try {
if (-not [System.IO.Path]::IsPathRooted($target)) {
$parent = [System.IO.Path]::GetDirectoryName($Path)
if ([string]::IsNullOrEmpty($parent)) { return $null }
$target = [System.IO.Path]::Combine($parent, $target)
}
$target = [System.IO.Path]::GetFullPath($target)
} catch { return $null }
# Compare like against like: $target went through GetFullPath, so $Path must
# too, or a relative spelling misses the self-reference guard and loops.
$self = $Path
try { $self = [System.IO.Path]::GetFullPath($Path) } catch { $self = $Path }
if ([string]::Equals(
$target.TrimEnd('\', '/'), $self.TrimEnd('\', '/'), [System.StringComparison]::OrdinalIgnoreCase
)) {
return $null
}
return $target
}
# Compiler-free stand-in for the native resolver. Normalized, not exact: it
# cannot expand an 8.3 alias or recover stored casing, so callers are told the
# answer is inexact. Never throws; an identity nobody can establish must not
# stop an install.
$script:StudioSubstMap = $null
function Get-StudioSubstTarget {
param([Parameter(Mandatory = $true)][string]$Path)
# A SUBST drive is a DOS device mapping and no 5.1 API reports it: measured