-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInstall-ClickOnce.ps1
More file actions
407 lines (351 loc) · 14.4 KB
/
Copy pathInstall-ClickOnce.ps1
File metadata and controls
407 lines (351 loc) · 14.4 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
param(
[string]$SourcePath,
[string]$InstallRoot = "$env:LOCALAPPDATA\lifeviz-clickonce",
[switch]$SkipCacheClear,
[switch]$RegisterClickOnce,
[switch]$NoLaunch,
[int]$WaitForProcessId = 0
)
$ErrorActionPreference = 'Stop'
function Resolve-Source {
param([string]$PathArg)
if ($PathArg) {
return (Resolve-Path $PathArg).Path
}
# Default to the directory that contains this script (expected to be the ClickOnce publish payload).
return (Split-Path -Parent $MyInvocation.MyCommand.Path)
}
function Resolve-Mage {
$candidates = @(
"$env:WINDIR\Microsoft.NET\Framework64\v4.0.30319\mage.exe",
"$env:WINDIR\Microsoft.NET\Framework\v4.0.30319\mage.exe"
)
foreach ($path in $candidates) {
if (Test-Path $path) { return $path }
}
return $null
}
function Resolve-StagedApplicationExe {
param([string]$ManifestPath)
[xml]$xml = Get-Content $ManifestPath
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("asmv1","urn:schemas-microsoft-com:asm.v1")
$ns.AddNamespace("asmv2","urn:schemas-microsoft-com:asm.v2")
$dependency = $xml.SelectSingleNode("//asmv2:dependentAssembly[contains(@codebase,'.manifest')]", $ns)
if ($dependency -and $dependency.codebase) {
$appManifest = Join-Path (Split-Path -Parent $ManifestPath) $dependency.codebase
if (Test-Path $appManifest) {
$appDir = Split-Path -Parent $appManifest
$exe = Join-Path $appDir 'lifeviz.exe'
if (Test-Path $exe) {
return (Resolve-Path $exe).Path
}
}
}
$applicationFiles = Join-Path (Split-Path -Parent $ManifestPath) 'Application Files'
$candidate = Get-ChildItem -Path $applicationFiles -Recurse -Filter 'lifeviz.exe' -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($candidate) {
return $candidate.FullName
}
throw "Could not resolve staged lifeviz.exe from $ManifestPath"
}
function Remove-ClickOnceShortcuts {
$roots = @(
(Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs'),
([Environment]::GetFolderPath('DesktopDirectory'))
) | Where-Object { $_ -and (Test-Path $_) }
foreach ($rootPath in $roots) {
Get-ChildItem -Path $rootPath -Recurse -Filter '*.appref-ms' -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match 'lifeviz' -or $_.FullName -match 'lifeviz' } |
Remove-Item -Force -ErrorAction SilentlyContinue
}
$clickOnceFolder = Join-Path (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs') 'lifeviz'
if ((Test-Path $clickOnceFolder) -and -not (Get-ChildItem -Path $clickOnceFolder -Force -ErrorAction SilentlyContinue)) {
Remove-Item -Path $clickOnceFolder -Force -ErrorAction SilentlyContinue
}
}
function New-LifeVizShortcut {
param(
[string]$ShortcutPath,
[string]$TargetPath
)
$parent = Split-Path -Parent $ShortcutPath
if (-not (Test-Path $parent)) {
New-Item -ItemType Directory -Force -Path $parent | Out-Null
}
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($ShortcutPath)
$shortcut.TargetPath = $TargetPath
$shortcut.WorkingDirectory = Split-Path -Parent $TargetPath
$shortcut.IconLocation = "$TargetPath,0"
$shortcut.Save()
}
function Install-DirectShortcuts {
param([string]$TargetPath)
Remove-ClickOnceShortcuts
$programs = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs'
$startShortcut = Join-Path $programs 'LifeViz.lnk'
$legacyLocalShortcut = Join-Path $programs 'LifeViz (Local).lnk'
$desktopShortcut = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) 'LifeViz.lnk'
New-LifeVizShortcut -ShortcutPath $startShortcut -TargetPath $TargetPath
New-LifeVizShortcut -ShortcutPath $desktopShortcut -TargetPath $TargetPath
if (Test-Path $legacyLocalShortcut) {
Remove-Item -Path $legacyLocalShortcut -Force -ErrorAction SilentlyContinue
}
Write-Host "[install] Start Menu shortcut: $startShortcut" -ForegroundColor Cyan
Write-Host "[install] Desktop shortcut: $desktopShortcut" -ForegroundColor Cyan
}
function Wait-ForStagedLifeVizProcesses {
param(
[string]$StagedRoot,
[int]$ExplicitProcessId
)
$rootPath = [IO.Path]::GetFullPath($StagedRoot).TrimEnd(
[IO.Path]::DirectorySeparatorChar,
[IO.Path]::AltDirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
$processIds = @()
if ($ExplicitProcessId -gt 0 -and $ExplicitProcessId -ne $PID) {
$explicitProcess = Get-Process -Id $ExplicitProcessId -ErrorAction SilentlyContinue
if ($explicitProcess) {
try {
$explicitPath = $explicitProcess.Path
if ($explicitProcess.ProcessName -eq 'lifeviz' -and
$explicitPath -and
$explicitPath.StartsWith($rootPath, [StringComparison]::OrdinalIgnoreCase)) {
$processIds += $ExplicitProcessId
}
} catch {}
}
}
Get-Process -Name 'lifeviz' -ErrorAction SilentlyContinue | ForEach-Object {
try {
$candidatePath = $_.Path
if ($candidatePath -and $candidatePath.StartsWith($rootPath, [StringComparison]::OrdinalIgnoreCase)) {
$processIds += $_.Id
}
} catch {}
}
foreach ($processId in ($processIds | Sort-Object -Unique)) {
$process = Get-Process -Id $processId -ErrorAction SilentlyContinue
if (-not $process) {
continue
}
Write-Host "[install] Waiting for running LifeViz process $processId to exit..." -ForegroundColor Cyan
if (-not $process.WaitForExit(60000)) {
throw "LifeViz process $processId did not exit within 60 seconds. Close LifeViz and run the installer again."
}
}
if ($processIds.Count -gt 0) {
Start-Sleep -Milliseconds 300
}
}
function Remove-DirectoryWithRetry {
param(
[string]$Path,
[int]$MaxAttempts = 20
)
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
if (-not (Test-Path -LiteralPath $Path)) {
return
}
try {
Remove-Item -Recurse -Force -LiteralPath $Path
return
} catch {
if (-not (Test-Path -LiteralPath $Path)) {
return
}
if ($attempt -eq $MaxAttempts) {
throw
}
Start-Sleep -Milliseconds 250
}
}
}
function Move-DirectoryWithRetry {
param(
[string]$Source,
[string]$Destination,
[int]$MaxAttempts = 10
)
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
try {
Move-Item -LiteralPath $Source -Destination $Destination
return
} catch {
if ($attempt -eq $MaxAttempts) {
throw "Failed to move '$Source' to '$Destination' after $MaxAttempts attempts: $_"
}
Start-Sleep -Milliseconds 250
}
}
}
function Copy-PayloadWithRetry {
param(
[string]$Source,
[string]$Destination,
[int]$MaxAttempts = 5
)
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
$robocopyLog = [IO.Path]::GetTempFileName()
$robocode = 16
$details = ''
try {
$robocopyArgs = @(
$Source,
$Destination,
'/E',
'/R:1',
'/W:1',
'/NFL',
'/NDL',
'/NC',
'/NS',
'/NP',
'/XF',
'payload.zip'
)
robocopy @robocopyArgs | Tee-Object -FilePath $robocopyLog | Out-Null
$robocode = $LASTEXITCODE
if (Test-Path -LiteralPath $robocopyLog) {
$details = Get-Content -Raw -LiteralPath $robocopyLog
}
} finally {
if (Test-Path -LiteralPath $robocopyLog) {
Remove-Item -LiteralPath $robocopyLog -Force -ErrorAction SilentlyContinue
}
}
if ($robocode -le 7) {
return
}
if ($attempt -eq $MaxAttempts) {
throw "robocopy failed with exit code $robocode after $MaxAttempts attempts.`n$details"
}
Write-Warning "Payload copy attempt $attempt failed with robocopy exit code $robocode; retrying."
Start-Sleep -Milliseconds (500 * $attempt)
}
}
function Promote-ValidatedPayload {
param(
[string]$StagingRoot,
[string]$InstallRoot,
[string]$BackupRoot
)
$backupCreated = $false
if (Test-Path -LiteralPath $InstallRoot) {
Write-Host "[install] Moving previous install to rollback backup: $BackupRoot" -ForegroundColor Cyan
Move-DirectoryWithRetry -Source $InstallRoot -Destination $BackupRoot
$backupCreated = $true
}
try {
Move-DirectoryWithRetry -Source $StagingRoot -Destination $InstallRoot
$promotedManifest = Join-Path $InstallRoot 'lifeviz.application'
if (-not (Test-Path -LiteralPath $promotedManifest)) {
throw "Promoted payload is missing its manifest at $promotedManifest"
}
$null = Resolve-StagedApplicationExe -ManifestPath $promotedManifest
} catch {
$promotionError = $_
if ($backupCreated) {
Write-Warning "New payload promotion failed; restoring the previous install from $BackupRoot."
if (Test-Path -LiteralPath $InstallRoot) {
Remove-DirectoryWithRetry -Path $InstallRoot
}
Move-DirectoryWithRetry -Source $BackupRoot -Destination $InstallRoot
$backupCreated = $false
}
throw $promotionError
}
if ($backupCreated -and (Test-Path -LiteralPath $BackupRoot)) {
try {
Remove-DirectoryWithRetry -Path $BackupRoot
} catch {
Write-Warning "The new install is active, but rollback-backup cleanup failed at ${BackupRoot}: $_"
}
}
}
$payloadRoot = Resolve-Source $SourcePath
$manifest = Join-Path $payloadRoot 'lifeviz.application'
if (-not (Test-Path $manifest)) {
throw "lifeviz.application not found under $payloadRoot. Point -SourcePath at the published ClickOnce folder."
}
Write-Host "[install] Payload root: $payloadRoot" -ForegroundColor Cyan
Write-Host "[install] Target location: $InstallRoot" -ForegroundColor Cyan
$InstallRoot = [IO.Path]::GetFullPath($InstallRoot).TrimEnd(
[IO.Path]::DirectorySeparatorChar,
[IO.Path]::AltDirectorySeparatorChar)
$stagingPrefix = "$InstallRoot.installing-"
$stagingRoot = $stagingPrefix + [Guid]::NewGuid().ToString('N')
$backupPrefix = "$InstallRoot.backup-"
$backupRoot = $backupPrefix + [Guid]::NewGuid().ToString('N')
if (-not $stagingRoot.StartsWith($stagingPrefix, [StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to stage outside the install-root sibling path: $stagingRoot"
}
if (-not $backupRoot.StartsWith($backupPrefix, [StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to back up outside the install-root sibling path: $backupRoot"
}
$promoted = $false
try {
New-Item -ItemType Directory -Force -Path $stagingRoot | Out-Null
Write-Host "[install] Copying new payload to transaction staging: $stagingRoot" -ForegroundColor Cyan
Copy-PayloadWithRetry -Source $payloadRoot -Destination $stagingRoot
$candidateManifest = Join-Path $stagingRoot 'lifeviz.application'
if (-not (Test-Path -LiteralPath $candidateManifest)) {
throw "Copied payload is missing its manifest at $candidateManifest"
}
$null = Resolve-StagedApplicationExe -ManifestPath $candidateManifest
Wait-ForStagedLifeVizProcesses -StagedRoot $InstallRoot -ExplicitProcessId $WaitForProcessId
if ($RegisterClickOnce -and -not $SkipCacheClear) {
$mage = Resolve-Mage
if ($mage) {
Write-Host "[install] Clearing ClickOnce cache (mage -cc) to avoid prior subscription conflicts..." -ForegroundColor Cyan
& $mage -cc | Out-Null
} else {
Write-Warning "mage.exe not found; skipping ClickOnce cache clear. If install complains about a different location, re-run with mage installed or uninstall the previous LifeViz entry first."
}
}
Promote-ValidatedPayload -StagingRoot $stagingRoot -InstallRoot $InstallRoot -BackupRoot $backupRoot
$promoted = $true
} catch {
if (-not $promoted -and (Test-Path -LiteralPath $stagingRoot)) {
Remove-DirectoryWithRetry -Path $stagingRoot -MaxAttempts 4
}
throw
}
$stagedManifest = Join-Path $InstallRoot 'lifeviz.application'
if (-not (Test-Path $stagedManifest)) {
throw "Staged manifest missing at $stagedManifest"
}
# Stamp a stable deployment provider URI so installs/updates always point to the same path.
try {
[xml]$xml = Get-Content $stagedManifest
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("asmv1","urn:schemas-microsoft-com:asm.v1")
$ns.AddNamespace("asmv2","urn:schemas-microsoft-com:asm.v2")
$providerNode = $xml.SelectSingleNode("//asmv2:deploymentProvider", $ns)
if (-not $providerNode) {
$providerNode = $xml.CreateElement("deploymentProvider","urn:schemas-microsoft-com:asm.v2")
$deployNode = $xml.SelectSingleNode("//asmv2:deployment",$ns)
if ($deployNode) { $deployNode.AppendChild($providerNode) | Out-Null }
}
if ($providerNode) {
$providerUri = (New-Object System.Uri((Resolve-Path $stagedManifest).Path)).AbsoluteUri
$null = $providerNode.SetAttribute("codebase",$providerUri)
$xml.Save($stagedManifest)
}
} catch {
Write-Warning "Failed to stamp stable deployment provider URI: $_"
}
$stagedExe = Resolve-StagedApplicationExe -ManifestPath $stagedManifest
Install-DirectShortcuts -TargetPath $stagedExe
if ($NoLaunch) {
Write-Host "[install] Launch skipped. Use the LifeViz Start Menu shortcut to run $stagedExe" -ForegroundColor Cyan
} elseif ($RegisterClickOnce) {
Write-Host "[install] Launching ClickOnce manifest from $stagedManifest" -ForegroundColor Cyan
Start-Process -FilePath $stagedManifest
} else {
Write-Host "[install] Launching staged app directly from $stagedExe" -ForegroundColor Cyan
Start-Process -FilePath $stagedExe -WorkingDirectory (Split-Path -Parent $stagedExe)
}