Files
xieyi-weixin-/installer_close_app.ps1
T
2026-09-28 10:02:07 +08:00

125 lines
4.9 KiB
PowerShell

param(
[Parameter(Mandatory = $true)][string]$InstallDir,
[ValidateRange(0, 60)][int]$GraceSeconds = 8,
[ValidateRange(1, 60)][int]$ForceSeconds = 10
)
# Extracted to the NSIS temporary directory, never the app folder.
# ASCII source also works with Windows PowerShell 5.1's default encoding.
$ErrorActionPreference = "Stop"
try {
$installRoot = [IO.Path]::GetFullPath($InstallDir).TrimEnd('\', '/')
if (-not [IO.Path]::IsPathRooted($InstallDir) -or
$installRoot -eq [IO.Path]::GetPathRoot($installRoot).TrimEnd('\', '/')) {
throw "An absolute application installation directory is required."
}
$runtimeRoot = $installRoot + '\_internal\'
$comparison = [StringComparison]::OrdinalIgnoreCase
$legacyExe = ([string][char]0x7504) + 'AI' + [char]0x5BA2 + [char]0x670D + '.exe'
function Test-AppExecutable([string]$ExecutablePath) {
if (-not $ExecutablePath) { return $false }
$fullPath = [IO.Path]::GetFullPath($ExecutablePath)
if ($fullPath.StartsWith($runtimeRoot, $comparison)) { return $true }
if (-not [IO.Path]::GetDirectoryName($fullPath).Equals($installRoot, $comparison)) {
return $false
}
$name = [IO.Path]::GetFileName($fullPath)
return ($name -like 'ZhenAI-WeCom-Assistant-v*.exe' -or $name -eq $legacyExe)
}
function Get-AppProcesses {
foreach ($candidate in [Diagnostics.Process]::GetProcesses()) {
$keep = $false
try {
if ($candidate.Id -ne $PID -and (Test-AppExecutable $candidate.MainModule.FileName)) {
# Hold the handle so a reused PID cannot target another process.
$null = $candidate.Handle
$keep = $true
$candidate
}
}
catch {
# Some system/elevated processes cannot be queried. File preflight
# below still rejects locks held by inaccessible processes.
}
finally {
if (-not $keep) { $candidate.Dispose() }
}
}
}
$initial = @(Get-AppProcesses)
try {
foreach ($running in $initial) {
try {
if (-not $running.HasExited) { $null = $running.CloseMainWindow() }
}
catch {
if (-not $running.HasExited) { Write-Output "Graceful close unavailable for PID $($running.Id)." }
}
}
$graceTimer = [Diagnostics.Stopwatch]::StartNew()
while ($graceTimer.Elapsed.TotalSeconds -lt $GraceSeconds) {
$alive = @($initial | Where-Object { -not $_.HasExited })
if ($alive.Count -eq 0) { break }
Start-Sleep -Milliseconds 200
}
}
finally {
foreach ($running in $initial) { $running.Dispose() }
}
# Closing the window may only hide the app in the tray. Re-enumerate to
# include WebEngine workers left behind or spawned during graceful close.
$forceTimer = [Diagnostics.Stopwatch]::StartNew()
while ($true) {
$remaining = @(Get-AppProcesses)
try {
if ($remaining.Count -eq 0) { break }
if ($forceTimer.Elapsed.TotalSeconds -ge $ForceSeconds) {
throw "Application processes did not exit before the timeout."
}
foreach ($running in $remaining) {
try {
if (-not $running.HasExited) {
Write-Output "Stopping installed application PID $($running.Id)."
$running.Kill()
}
}
catch {
if (-not $running.HasExited) { throw }
}
}
}
finally {
foreach ($running in $remaining) { $running.Dispose() }
}
Start-Sleep -Milliseconds 200
}
# Check all files before NSIS removes anything, including locks held by
# external tools/elevated processes that a per-user installer cannot close.
if (Test-Path -LiteralPath $installRoot) {
$files = @(Get-ChildItem -LiteralPath $installRoot -File -Force | Where-Object {
$_.Name -like 'ZhenAI-WeCom-Assistant-v*.exe' -or
$_.Name -eq $legacyExe -or $_.Name -eq 'ZhenAIUpdater.exe'
})
$runtimeDir = Join-Path $installRoot '_internal'
if (Test-Path -LiteralPath $runtimeDir) {
$files += @(Get-ChildItem -LiteralPath $runtimeDir -File -Recurse -Force)
}
foreach ($file in $files) {
$stream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open,
[IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
$stream.Dispose()
}
}
Write-Output "Installed application stopped; files are ready for replacement."
exit 0
}
catch {
Write-Output ("Cannot prepare installed application: " + $_.Exception.Message)
exit 1
}