Files
8x8-Work-updater/8x8_Work_Updater.ps1
T
2026-08-25 09:07:51 +01:00

294 lines
12 KiB
PowerShell

# ==============================================================================
# Script Name: 8x8_Work_Updater.ps1
# Description: Downloads 8x8 with a progress bar, detects the active interactive
# desktop user dynamically, presents the unclosable HTA countdown
# prompt, installs silently, and relaunches 8x8 Work.
# ==============================================================================
# Ensure script is running elevated
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "This script must be executed with Administrator privileges."
exit 1
}
Add-Type -AssemblyName System.Net.Http
$workDir = "C:\ProgramData\JCT600_8x8Update"
$flagFile = Join-Path $workDir "8x8_Update_Proceed.flag"
$htaPromptPath = Join-Path $workDir "Show-8x8Prompt.hta"
$installerPath = Join-Path $workDir "8x8_Work_Installer.msi"
if (-not (Test-Path $workDir)) {
New-Item -Path $workDir -ItemType Directory -Force | Out-Null
}
$acl = Get-Acl $workDir
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $workDir $acl
if (Test-Path $flagFile) { Remove-Item $flagFile -Force }
try {
# --------------------------------------------------------------------------
# Step 1: Download 8x8 Setup Installer with Console Progress Bar
# --------------------------------------------------------------------------
$installerUrl = "https://work-desktop-assets.8x8.com/prod-publish/ga/work-64-msi-v8.36.2-3.msi"
Write-Host "[1/4] Downloading 8x8 Work installer..." -ForegroundColor Cyan
try {
$httpClient = New-Object System.Net.Http.HttpClient
$response = $httpClient.GetAsync($installerUrl, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).Result
if (-not $response.IsSuccessStatusCode) { throw "HTTP Error $($response.StatusCode)" }
$totalBytes = $response.Content.Headers.ContentLength
$inputStream = $response.Content.ReadAsStreamAsync().Result
$outputStream = [System.IO.File]::Create($installerPath)
$buffer = New-Object byte[] 8192
$totalBytesRead = 0; $bytesRead = 0
while (($bytesRead = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
$outputStream.Write($buffer, 0, $bytesRead)
$totalBytesRead += $bytesRead
if ($totalBytes -gt 0) {
$percent = [math]::Round(($totalBytesRead / $totalBytes) * 100)
$downloadedMB = [math]::Round($totalBytesRead / 1MB, 2)
$totalMB = [math]::Round($totalBytes / 1MB, 2)
$barLength = 30
$filledLength = [math]::Round(($percent / 100) * $barLength)
$bar = ("#" * $filledLength) + ("-" * ($barLength - $filledLength))
Write-Host "`rDownloading: [$bar] $percent% ($downloadedMB MB / $totalMB MB)" -NoNewline -ForegroundColor Yellow
}
}
$outputStream.Close(); $inputStream.Close(); $httpClient.Dispose()
Write-Host "`nDownload complete: $installerPath" -ForegroundColor Green
} catch {
Write-Error "`nFailed to download installer. Error: $_"
exit 1
}
# --------------------------------------------------------------------------
# Step 2: Generate Sleep-Safe Wall-Clock HTA Countdown Dialog
# --------------------------------------------------------------------------
Write-Host "[2/4] Generating sleep-safe unclosable dialog..." -ForegroundColor Cyan
$htaContent = @"
<!DOCTYPE html>
<html>
<head>
<title>JCT600 IT Support — 8x8 Work Update</title>
<HTA:APPLICATION
ID="o8x8Update"
APPLICATIONNAME="JCT600 8x8 Work Update"
BORDER="dialog"
BORDERSTYLE="normal"
CAPTION="yes"
CONTEXTMENU="no"
ICON=""
INNERBORDER="no"
MAXIMIZEBUTTON="no"
MINIMIZEBUTTON="no"
NAVIGABLE="no"
SCROLL="no"
SCROLLFLAT="no"
SELECTION="no"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
SYSMENU="no"
WINDOWSTATE="normal"
/>
<style>
body {
background-color: #F0F2F5;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 20px;
text-align: center;
user-select: none;
}
.header {
color: #002B49;
font-size: 17px;
font-weight: bold;
margin-bottom: 8px;
}
.message {
color: #333333;
font-size: 13px;
line-height: 1.4;
margin-bottom: 15px;
}
.timer {
color: #C00000;
font-size: 32px;
font-weight: bold;
margin-bottom: 18px;
letter-spacing: 2px;
}
.btn-update {
background-color: #002B49;
color: #FFFFFF;
font-size: 14px;
font-weight: bold;
padding: 10px 32px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn-update:hover {
background-color: #004B7D;
}
</style>
<script language="javascript">
var targetTime = new Date().getTime() + (3600 * 1000);
function initWindow() {
window.resizeTo(480, 270);
window.moveTo((screen.width - 480) / 2, (screen.height - 270) / 2);
tick();
setInterval(tick, 1000);
}
function tick() {
var now = new Date().getTime();
var remainingMilliseconds = targetTime - now;
var totalSeconds = Math.floor(remainingMilliseconds / 1000);
if (totalSeconds > 0) {
var mins = Math.floor(totalSeconds / 60);
var secs = totalSeconds % 60;
var formattedMins = mins < 10 ? "0" + mins : mins;
var formattedSecs = secs < 10 ? "0" + secs : secs;
document.getElementById("timerDisplay").innerText = formattedMins + ":" + formattedSecs;
} else {
proceedUpdate();
}
}
function proceedUpdate() {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.CreateTextFile("$($flagFile.Replace('\', '\\'))", true);
file.WriteLine("proceed");
file.Close();
} catch(e) {}
window.close();
}
</script>
</head>
<body onload="initWindow()">
<div class="header">JCT600 — IT SUPPORT</div>
<div class="message">
An automatic update for 8x8 Work has been scheduled.<br>
Please save active work or click <b>Update Now</b> to begin.
</div>
<div class="timer" id="timerDisplay">60:00</div>
<button class="btn-update" onclick="proceedUpdate()">Update Now</button>
</body>
</html>
"@
[System.IO.File]::WriteAllText($htaPromptPath, $htaContent, [System.Text.Encoding]::ASCII)
# --------------------------------------------------------------------------
# Step 3: Detect Active Desktop User & Launch HTA Prompt
# --------------------------------------------------------------------------
Write-Host "[3/4] Detecting active console user and launching dialog..." -ForegroundColor Cyan
$explorerProc = Get-Process -Name explorer -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $explorerProc) {
Write-Warning "No active interactive desktop detected. Proceeding directly to update."
} else {
# Query owner domain\username directly from explorer process
$ownerInfo = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $($explorerProc.Id)" | Invoke-CimMethod -MethodName GetOwner
$activeUser = "$($ownerInfo.Domain)\$($ownerInfo.User)"
Write-Host "Active Desktop User: $activeUser" -ForegroundColor Green
$taskName = "JCT600_8x8_UpdatePrompt"
# Register Scheduled Task targeting the interactive token of the active user
$action = New-ScheduledTaskAction -Execute "mshta.exe" -Argument "`"$htaPromptPath`""
$trigger = New-ScheduledTaskTrigger -At (Get-Date).AddSeconds(2) -Once
$principal = New-ScheduledTaskPrincipal -UserId $activeUser -LogonType Interactive -RunLevel Limited
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Hours 2)
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
Start-ScheduledTask -TaskName $taskName | Out-Null
Write-Host "Dialog prompt active. Waiting for user action or 1-hour expiration..." -ForegroundColor Yellow
while (-not (Test-Path $flagFile)) {
Start-Sleep -Seconds 2
}
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
# --------------------------------------------------------------------------
# Step 4: Close 8x8 Processes & Install Silently
# --------------------------------------------------------------------------
Write-Host "[4/4] Stopping 8x8 processes and installing silently..." -ForegroundColor Cyan
$targetProcesses = Get-Process | Where-Object {
$_.ProcessName -like "*8x8*" -or $_.MainWindowTitle -like "*8x8*"
}
if ($targetProcesses) {
foreach ($proc in $targetProcesses) {
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
}
Start-Sleep -Seconds 3
}
$msiArgs = "/i `"$installerPath`" /quiet /norestart"
$installJob = Start-Process msiexec.exe -ArgumentList $msiArgs -Wait -PassThru
if ($installJob.ExitCode -ne 0 -and $installJob.ExitCode -ne 3010) {
Write-Error "Installation failed with exit code $($installJob.ExitCode)."
exit $installJob.ExitCode
}
Write-Host "Installation completed successfully." -ForegroundColor Green
# --------------------------------------------------------------------------
# Step 5: Relaunch 8x8 Work in Active User Session
# --------------------------------------------------------------------------
Write-Host "Launching 8x8 Work..." -ForegroundColor Cyan
$possiblePaths = @(
"${env:ProgramFiles}\8x8 Inc\8x8 Work\8x8 Work.exe",
"${env:ProgramFiles(x86)}\8x8 Inc\8x8 Work\8x8 Work.exe",
"${env:ProgramFiles}\8x8 Work\8x8 Work.exe",
"$env:LocalAppData\Programs\8x8 Work\8x8 Work.exe"
)
$exePath = $possiblePaths | Where-Object { Test-Path $_ } | Select-Object -First 1
if ($exePath) {
if ($explorerProc -and $activeUser) {
$launchTask = "JCT600_8x8_Launch"
$launchAction = New-ScheduledTaskAction -Execute "explorer.exe" -Argument "`"$exePath`""
$launchTrigger = New-ScheduledTaskTrigger -At (Get-Date).AddSeconds(2) -Once
$launchPrincipal = New-ScheduledTaskPrincipal -UserId $activeUser -LogonType Interactive -RunLevel Limited
Register-ScheduledTask -TaskName $launchTask -Action $launchAction -Trigger $launchTrigger -Principal $launchPrincipal -Force | Out-Null
Start-ScheduledTask -TaskName $launchTask | Out-Null
Start-Sleep -Seconds 4
Unregister-ScheduledTask -TaskName $launchTask -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "8x8 Work launched successfully." -ForegroundColor Green
} else {
Start-Process "explorer.exe" -ArgumentList "`"$exePath`""
}
} else {
Write-Warning "Could not locate 8x8 Work executable."
}
} finally {
Write-Host "Cleaning up temporary files..." -ForegroundColor Gray
if (Test-Path $workDir) {
Remove-Item $workDir -Recurse -Force -ErrorAction SilentlyContinue
}
}