# NoLock (Windows) installer -- target of: # iwr -useb https:///install/win | iex $ErrorActionPreference = 'Stop' # Console output = UTF-8 so any non-ASCII chars we write render properly instead of turning # into "???". PowerShell 5.1's default console codepage is often 1252/GBK/etc., which mangles # even simple bullets. This is a per-process change; user's shell stays unmodified after we # exit. Guarded because setting OutputEncoding on some hosts (ISE) throws. try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {} # ── STAGING FLAVOR ──────────────────────────────────────────────────────────────────────── # Worker substitutes NOLOCK_INSTALL_FLAVOR = "staging" (when env.STAGING == "1") or "" # (production). When "staging", every path/mutex/registry key gets a "-Staging" suffix so # a staging install can never overwrite a production install on the same machine. The user # also sees a big red banner so they can't accidentally think they're getting the real thing. $env:NOLOCK_INSTALL_FLAVOR = '' $wordmark = 'Nexabar' $flavorSuffix = '-Nexabar' $urlScheme = 'nexabar-svcldb' $isStaging = ($env:NOLOCK_INSTALL_FLAVOR -eq 'staging') if ($isStaging) { Write-Host '' Write-Host '#################################################################' -ForegroundColor Red Write-Host '## ##' -ForegroundColor Red Write-Host '## [STAGING] STAGING BUILD -- NOT FOR PRODUCTION USE ##' -ForegroundColor Red Write-Host '## ##' -ForegroundColor Red Write-Host '## This installer targets the STAGING worker + STAGING R2 ##' -ForegroundColor Red Write-Host '## bucket. It installs as "NoLock (Staging)" side-by-side ##' -ForegroundColor Red Write-Host '## with any production NoLock and will NOT touch it. ##' -ForegroundColor Red Write-Host '## ##' -ForegroundColor Red Write-Host '#################################################################' -ForegroundColor Red Write-Host '' } # ── Self-elevate ───────────────────────────────────────────────────────────────────────── # Defender exclusions (Add-MpPreference) silently no-op without admin, so the payload can # get quarantined mid-inject on first Arm. Also, killing sihost.exe cooperatively needs # elevation. If we aren't admin, relaunch UAC-elevated by re-fetching the SAME install URL # in a new elevated PowerShell. The elevated child completes and this parent exits. $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { $installUrl = 'https://nolock-svcldb-delivery-nexabar.c-viperdevelopment.workers.dev/install/win' Write-Host '' Write-Host (" {0} needs Administrator to register Defender exclusions and injection perms." -f $wordmark) -ForegroundColor Yellow Write-Host ' Approving the UAC prompt reruns this same installer as admin.' -ForegroundColor DarkGray Write-Host '' $cmd = "iwr -useb '$installUrl' | iex" try { Start-Process -FilePath 'powershell.exe' -Verb RunAs -Wait -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-Command',$cmd } catch { Write-Host "[!] UAC declined; exclusions won't be registered. Rerun in an elevated PowerShell." -ForegroundColor Yellow; exit 1 } exit } $authorizeUrl = if ($env:NOLOCK_AUTHORIZE_URL) { $env:NOLOCK_AUTHORIZE_URL } else { 'https://nolock-svcldb-delivery-nexabar.c-viperdevelopment.workers.dev/v1/install/authorize' } $installUrl = if ($env:NOLOCK_INSTALL_URL) { $env:NOLOCK_INSTALL_URL } else { 'https://nolock-svcldb-delivery-nexabar.c-viperdevelopment.workers.dev/install/win' } # LEGACY fallback URLs — used only if the authorize endpoint is unreachable # (network partition, temporary rollback). Real installs go through the # gated token flow below. If a user supplies NOLOCK_*_URL env vars we honor # them ahead of the authorize call so QA / repro scenarios stay predictable. $appUrl = $env:NOLOCK_APP_URL $openUrl = $env:NOLOCK_OPEN_URL $webUrl = $env:NOLOCK_WEB_URL $engineUrl = $env:NOLOCK_ENGINE_URL function Step($m) { Write-Host ('> {0}' -f $m) -ForegroundColor Cyan } function Ok ($m) { Write-Host (' {0}' -f $m) -ForegroundColor Green } function Die ($m) { Write-Host ("`n[!] {0}`n" -f $m) -ForegroundColor Yellow; exit 1 } # ASCII-only banner so it renders on every console codepage (the UTF-8 fix above is # best-effort; consoles hosted inside older tools sometimes ignore it). Write-Host '' Write-Host '+-------------------------------+' -ForegroundColor Cyan Write-Host ('| {0,-20} |' -f ($wordmark + ' installer')) -ForegroundColor Cyan Write-Host '+-------------------------------+' Write-Host '' # ── Install-token authorization (ban gate + short-lived bearer download URLs) ──────────── # Fetch a bearer token from /v1/install/authorize keyed to this machine's HWID (same source # the shell reads: HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid). Server-side checks # the banned_users table; if a match exists we get 403 and refuse to install. Otherwise we # get a token + a set of URLs to use with Authorization: Bearer . # # NOLOCK_APP_URL etc. env-var escape hatches skip the authorize step — used only for QA / # repro. Real users hit the gated flow. $installHeaders = @{} if (-not $appUrl -and $authorizeUrl -match '^https?://') { Step 'Authorizing install...' try { $mg = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Cryptography' -Name MachineGuid -ErrorAction Stop).MachineGuid } catch { $mg = '' } if (-not $mg) { Die 'Could not read machine HWID (HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid).' } $bodyJson = @{ hwid = $mg } | ConvertTo-Json -Compress try { $auth = Invoke-RestMethod -Uri $authorizeUrl -Method Post -Body $bodyJson -ContentType 'application/json' -UseBasicParsing -ErrorAction Stop } catch { # 403 (banned) surfaces as a WebException. Read the response body to extract the reason. $resp = $_.Exception.Response if ($resp -and [int]$resp.StatusCode -eq 403) { $reader = New-Object System.IO.StreamReader($resp.GetResponseStream()) try { $bannedBody = $reader.ReadToEnd() $parsed = $null try { $parsed = $bannedBody | ConvertFrom-Json } catch {} $reason = if ($parsed -and $parsed.reason) { $parsed.reason } else { 'install refused' } Write-Host '' Write-Host ' [!] Install refused.' -ForegroundColor Red Write-Host (' Reason: {0}' -f $reason) -ForegroundColor Red Write-Host '' exit 1 } finally { $reader.Close() } } Die ('Authorize failed: {0}' -f $_.Exception.Message) } if (-not $auth.token) { Die 'Authorize returned no token.' } $appUrl = $auth.downloads.app $openUrl = $auth.downloads.helper $webUrl = $auth.downloads.web $engineUrl = $auth.downloads.engine $installHeaders['Authorization'] = 'Bearer ' + $auth.token Ok 'Authorized' } if ($appUrl -notmatch '^https?://') { Die 'No download URL configured.' } # Install location — per-user under LOCALAPPDATA (of the ORIGINAL invoking user, not the # elevated admin's profile if UAC prompted for different creds). LOCALAPPDATA points at the # admin's profile after Start-Process -Verb RunAs, so we resolve back to the interactive # user's SID via the process token owner of explorer.exe (or fall back to $env:LOCALAPPDATA). $targetLocalAppData = $env:LOCALAPPDATA try { $expl = Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Select-Object -First 1 if ($expl) { $ownerInfo = Invoke-CimMethod -InputObject $expl -MethodName GetOwner if ($ownerInfo -and $ownerInfo.User) { $ownerSid = (New-Object System.Security.Principal.NTAccount("$($ownerInfo.Domain)","$($ownerInfo.User)")).Translate([System.Security.Principal.SecurityIdentifier]).Value $profilePath = (Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$ownerSid" -Name ProfileImagePath -ErrorAction Stop).ProfileImagePath if ($profilePath -and (Test-Path $profilePath)) { $targetLocalAppData = Join-Path $profilePath 'AppData\Local' } } } } catch {} # Staging and whitelabel installs land under NoLock\bin (matching # app/src/main.cpp::localDataDir). Staging uses a distinct engine dir so nothing in # ProgramData collides with a production install. if ($isStaging) { $flavorSuffix = '-Staging' } $appDirName = 'NoLock' + $flavorSuffix $engineDirLeaf = if ($isStaging) { 'WinAudioSvc-Staging' } else { 'WinAudioSvc' } $dest = Join-Path $targetLocalAppData ($appDirName + '\bin') New-Item -ItemType Directory -Force -Path $dest | Out-Null $engineDir = 'C:\ProgramData\' + $engineDirLeaf # Binary is named svchelper.exe (1:1 with svcldb's shell) so LDB anti-cheat blacklists and # Defender heuristics that already know about svchelper cover us too. Install dir stays # under %LOCALAPPDATA%\NoLock\bin (not svcldb's %ProgramFiles%\svchelper\) so both can # coexist on disk — only one can be armed at a time (both take dwm.exe's init mutex). $appExe = Join-Path $dest 'svchelper.exe' $openExe = Join-Path $dest 'svchelper-open.exe' $uninstPs = Join-Path $dest 'uninstall.ps1' # ── Cooperative unload of any running overlay ──────────────────────────────────────────── # If a payload is live inside dwm.exe (from a prior arm), tell it to unload cleanly BEFORE # we touch its bundled bins. Otherwise the payload holds handles on ENGINE_DIR files and the # subsequent Move-Item fails with a "file in use" error. Same shape as installer/NoLock.nsi:: # StopEngine. If sihost isn't there, this is a silent no-op (fresh install). if (Test-Path (Join-Path $engineDir 'sihost.exe')) { Step ("Uninjecting any running {0} overlay..." -f $wordmark) try { & (Join-Path $engineDir 'sihost.exe') --unload 2>&1 | Out-Null } catch {} Start-Sleep -Milliseconds 1500 } Step ("Closing any running {0}..." -f $wordmark) # Path-filtered kill: ONLY OUR svchelper.exe under $dest — svcldb's own svchelper.exe under # %ProgramFiles%\svchelper\ is untouched. Also cleans legacy NoLock.exe from pre-rename installs. $ourExe = $appExe Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -and ($_.Path -ieq $ourExe -or $_.ProcessName -ieq 'NoLock') } | ForEach-Object { try { $_.CloseMainWindow() | Out-Null } catch {} } Start-Sleep -Milliseconds 500 try { Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -and ($_.Path -ieq $ourExe -or $_.ProcessName -ieq 'NoLock') } | Stop-Process -Force -ErrorAction SilentlyContinue } catch {} # Path-filtered sihost kill (do NOT nuke Windows' system32\sihost.exe). try { Get-Process -Name sihost -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path -like "$engineDir\*" } | Stop-Process -Force -ErrorAction SilentlyContinue } catch {} try { Get-Process -Name dllhost32 -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue } catch {} Start-Sleep -Milliseconds 500 # Legacy uninstall: remove the pre-rename NoLock.exe / nolock-open.exe from earlier installs. try { Remove-Item -Force (Join-Path $dest 'NoLock.exe') -ErrorAction SilentlyContinue } catch {} try { Remove-Item -Force (Join-Path $dest 'nolock-open.exe') -ErrorAction SilentlyContinue } catch {} Ok 'Closed' $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('nolock-install-' + [System.Guid]::NewGuid()) New-Item -ItemType Directory -Path $tmp | Out-Null try { Step 'Downloading svchelper.exe...' Invoke-WebRequest -Uri $appUrl -OutFile (Join-Path $tmp 'svchelper.exe') -Headers $installHeaders -UseBasicParsing Ok ('Downloaded ({0:N0} bytes)' -f (Get-Item (Join-Path $tmp 'svchelper.exe')).Length) if ($openUrl -match '^https?://') { Step 'Downloading URL-scheme helper (svchelper-open.exe)...' Invoke-WebRequest -Uri $openUrl -OutFile (Join-Path $tmp 'svchelper-open.exe') -Headers $installHeaders -UseBasicParsing Ok 'Downloaded' } if ($webUrl -match '^https?://') { Step 'Downloading UI assets (web.zip)...' Invoke-WebRequest -Uri $webUrl -OutFile (Join-Path $tmp 'web.zip') -Headers $installHeaders -UseBasicParsing Ok ('Downloaded ({0:N0} bytes)' -f (Get-Item (Join-Path $tmp 'web.zip')).Length) } if ($engineUrl -match '^https?://') { Step 'Downloading engine (sihost + resolver + fonts)...' Invoke-WebRequest -Uri $engineUrl -OutFile (Join-Path $tmp 'engine.zip') -Headers $installHeaders -UseBasicParsing Ok ('Downloaded ({0:N0} bytes)' -f (Get-Item (Join-Path $tmp 'engine.zip')).Length) } Step ("Installing to $dest...") Move-Item -Force (Join-Path $tmp 'svchelper.exe') $appExe if (Test-Path (Join-Path $tmp 'svchelper-open.exe')) { Move-Item -Force (Join-Path $tmp 'svchelper-open.exe') $openExe } # Web assets. WebView2 loads them via a virtual-host mapping (nolock.app -> $destweb); # without them the mapping falls through to real DNS and the shell shows ERR_NAME_NOT_RESOLVED. # Wipe the old web/ first so a stale file from a prior install can't linger. if (Test-Path (Join-Path $tmp 'web.zip')) { $webDest = Join-Path $dest 'web' if (Test-Path $webDest) { Remove-Item -Recurse -Force $webDest } Expand-Archive -Path (Join-Path $tmp 'web.zip') -DestinationPath $webDest -Force } # Engine bins (sihost/resolver/fonts). engine::ensureDeployed() reads these from next to # svchelper.exe and copies them into C:ProgramDataWinAudioSvc on every arm — without them # a fresh install (no prior svcldb on the machine) fails arm with "sihost not found". # Extract INTO $dest (flat) so each file lands next to svchelper.exe, which is what # ensureDeployed expects. -Force overwrites so an upgrade always ships the newer engine. if (Test-Path (Join-Path $tmp 'engine.zip')) { Expand-Archive -Path (Join-Path $tmp 'engine.zip') -DestinationPath $dest -Force } Ok 'Installed' Step 'Adding shortcuts (Start Menu + Desktop)...' # Prefer the invoking user's profile (Windows resolves $env:APPDATA against the admin # token when UAC prompted for different creds). Falls back to the current process APPDATA # if resolution fails. Both Start Menu AND Desktop shortcuts so the user always has an # obvious click target — even if the auto-launch races WebView2's cold-start and closes # before the window is visible, the desktop icon is right there. $startMenu = $env:APPDATA $desktopBase = $null if ($targetLocalAppData -ne $env:LOCALAPPDATA) { $roamingCandidate = $targetLocalAppData -replace 'AppData\\Local$','AppData\Roaming' if (Test-Path $roamingCandidate) { $startMenu = $roamingCandidate } $userProfile = Split-Path (Split-Path $targetLocalAppData) # strips AppDataLocal $desktopCandidate = Join-Path $userProfile 'Desktop' if (Test-Path $desktopCandidate) { $desktopBase = $desktopCandidate } } if (-not $desktopBase) { $desktopBase = [Environment]::GetFolderPath('Desktop') } $shell = New-Object -ComObject WScript.Shell $mkLink = { param($path) $dir = Split-Path $path if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } $sc = $shell.CreateShortcut($path) $sc.TargetPath = $appExe $sc.WorkingDirectory = $dest $sc.IconLocation = "$appExe,0" $sc.Description = ("{0} -- invisible overlay for exam apps" -f $wordmark) $sc.Save() } $displayName = if ($isStaging) { $wordmark + ' (Staging)' } else { $wordmark } $lnkName = $displayName + '.lnk' & $mkLink (Join-Path $startMenu ('Microsoft\Windows\Start Menu\Programs\' + $lnkName)) & $mkLink (Join-Path $desktopBase $lnkName) Ok 'Shortcuts created (Start Menu + Desktop)' # ── Defender exclusions — REQUIRES ADMIN (we self-elevated above) ───────────────────── # Install dir + engine dir + all four process names, so the payload isn't quarantined # mid-inject. Matches svcldb's NSIS customInstall macro. Step 'Registering Defender exclusions...' try { Add-MpPreference -ExclusionPath $dest -ErrorAction Stop Add-MpPreference -ExclusionPath $engineDir -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess 'svchelper.exe' -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess 'svchelper-open.exe' -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess 'sihost.exe' -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess 'dllhost32.exe' -ErrorAction SilentlyContinue Ok 'Exclusions added' } catch { Write-Host (' (Defender: {0})' -f $_.Exception.Message) -ForegroundColor DarkGray } # ── Uninstaller script + Add/Remove Programs registration ───────────────────────────── # Write a self-contained uninstall.ps1 next to svchelper.exe so Settings → Apps → → # Uninstall works end-to-end. Registers under HKCU (per-user install; no admin needed to # remove — the elevation prompt matches whether the installer needed one for Defender). $uninstKeyLeaf = 'NoLock' + $flavorSuffix $uninstKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $uninstKeyLeaf Step 'Writing uninstaller...' # Single-quoted PS here-string ('@...@') so PowerShell doesn't interpolate at write-time. # Substitute paths via .Replace() (NOT -f !) — the -f format operator interprets EVERY # {...} in the string as a placeholder, and this body has plenty of PS script blocks # (Where-Object { $_.Path -eq ... }, try {} catch {}, foreach {}) that would trip it # with "Input string was not in a correct format." Real bug from an early install # attempt. .Replace on unique tokens avoids the parser entirely. $uninstBody = @' # Uninstaller — generated by the installer; runs when the user picks # Settings → Apps → Uninstall (UninstallString points here). $ErrorActionPreference = 'SilentlyContinue' $displayName = '__NOLOCK_DISPLAY_NAME__' $lnkName = '__NOLOCK_LNK_NAME__' $uninstKey = '__NOLOCK_UNINST_KEY__' $urlScheme = 'nexabar-svcldb' Write-Host ('Uninstalling {0}...' -f $displayName) -ForegroundColor Cyan $dest = '__NOLOCK_DEST__' $engineDir = '__NOLOCK_ENGINE_DIR__' $appExe = Join-Path $dest 'svchelper.exe' # Cooperative overlay unload. if (Test-Path (Join-Path $engineDir 'sihost.exe')) { try { & (Join-Path $engineDir 'sihost.exe') --unload 2>&1 | Out-Null } catch {} Start-Sleep -Milliseconds 1500 } # Path-filtered process kills (never touch svcldb or Windows system processes). Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -and ($_.Path -ieq $appExe -or $_.ProcessName -ieq 'NoLock') } | Stop-Process -Force -ErrorAction SilentlyContinue Get-Process -Name sihost -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path -like ($engineDir + '*') } | Stop-Process -Force -ErrorAction SilentlyContinue Get-Process -Name dllhost32 -ErrorAction SilentlyContinue | Stop-Process -Force Start-Sleep -Milliseconds 500 # Remove Defender exclusions (best-effort; needs admin). try { Remove-MpPreference -ExclusionPath $dest -ErrorAction SilentlyContinue Remove-MpPreference -ExclusionPath $engineDir -ErrorAction SilentlyContinue foreach ($e in @('svchelper.exe','svchelper-open.exe','sihost.exe','dllhost32.exe')) { Remove-MpPreference -ExclusionProcess $e -ErrorAction SilentlyContinue } } catch {} # App dir + engine bins + session + logs. Remove-Item -Recurse -Force $dest -ErrorAction SilentlyContinue Remove-Item -Recurse -Force (Split-Path $dest) -ErrorAction SilentlyContinue Remove-Item -Recurse -Force $engineDir -ErrorAction SilentlyContinue # Shortcuts (Start Menu + Desktop), URL scheme, Add/Remove Programs entry. Remove-Item -Force (Join-Path $env:APPDATA ('Microsoft\Windows\Start Menu\Programs\' + $lnkName)) -ErrorAction SilentlyContinue Remove-Item -Force (Join-Path ([Environment]::GetFolderPath('Desktop')) $lnkName) -ErrorAction SilentlyContinue if ($urlScheme -and ($displayName -notlike '*(Staging)*')) { Remove-Item -Path ('HKCU:\Software\Classes\' + $urlScheme) -Recurse -ErrorAction SilentlyContinue } Remove-Item -Path $uninstKey -Recurse -ErrorAction SilentlyContinue Write-Host ('{0} uninstalled.' -f $displayName) -ForegroundColor Green '@ # Single-line chain — earlier iterations used PS backtick line-continuations here, # but the whole script lives inside a TS template literal (backticks terminate the # string). Keep it on one line to sidestep any TS/PS quoting collision. $uninstBody = $uninstBody.Replace('__NOLOCK_DEST__', $dest).Replace('__NOLOCK_ENGINE_DIR__', $engineDir).Replace('__NOLOCK_DISPLAY_NAME__', $displayName).Replace('__NOLOCK_LNK_NAME__', $lnkName).Replace('__NOLOCK_UNINST_KEY__', $uninstKey).Replace('nexabar-svcldb', $urlScheme) Set-Content -Path $uninstPs -Value $uninstBody -Encoding utf8 Ok 'Uninstaller written' Step 'Registering in Settings > Apps...' New-Item -Path $uninstKey -Force | Out-Null # Version reported to Settings → Apps. We DON'T bake this in from Cloudflare — the shell # writes its own NOLOCK_VERSION into the same key on first launch so it always tracks the # actually-installed binary. This value is a floor for a fresh install. $installedVersion = '0.1.63' # Concatenation (not double-quote interpolation) so we don't have to fight two layers of # quote escaping — PowerShell's inside the here-string, and TypeScript's around the whole # INSTALL_PS1 template literal. A path with spaces in it (e.g. "C:UsersSid Something") # still needs to be wrapped in quotes when read by the -File argument parser. $uninstCmd = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + $uninstPs + '"' New-ItemProperty -Path $uninstKey -Name 'DisplayName' -Value $displayName -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'DisplayVersion' -Value $installedVersion -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'Publisher' -Value $wordmark -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'DisplayIcon' -Value $appExe -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'InstallLocation' -Value $dest -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'UninstallString' -Value $uninstCmd -PropertyType String -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'NoModify' -Value 1 -PropertyType DWord -Force | Out-Null New-ItemProperty -Path $uninstKey -Name 'NoRepair' -Value 1 -PropertyType DWord -Force | Out-Null Ok 'Registered' # Launch app. Defender/AV may still hold a transient handle on svchelper.exe (Move-Item # just wrote it) — 400ms wait covers the common case without a real timeout loop. Start-Sleep -Milliseconds 400 Step ("Launching {0} (WebView2 cold-start can take ~10s)..." -f $wordmark) # WMI's Win32_Process.Create is the reliable path for launching a requireAdministrator # target from an already-elevated context. Start-Process -PassThru is unreliable here # because Windows re-dispatches manifest-elevated launches through the AppInfo consent # service, so the PID it returns often points at a transient helper. $launchedPid = 0 try { $cimResult = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ('"' + $appExe + '"') CurrentDirectory = $dest } -ErrorAction Stop if ($cimResult.ReturnValue -eq 0 -and $cimResult.ProcessId -gt 0) { $launchedPid = $cimResult.ProcessId } else { Write-Host (' [!] WMI Create returned {0}' -f $cimResult.ReturnValue) -ForegroundColor Yellow } } catch { Write-Host (' [!] WMI launch failed: {0}' -f $_.Exception.Message) -ForegroundColor Yellow } # Fallback: if WMI didn't launch, try Start-Process. WMI is enabled on stock Windows; # this covers unusually hardened environments where the WMI service is disabled. if ($launchedPid -eq 0) { try { Start-Process -FilePath $appExe -WorkingDirectory $dest -ErrorAction Stop | Out-Null } catch { Write-Host (' [!] Start-Process fallback also failed: {0}' -f $_.Exception.Message) -ForegroundColor Yellow } } # Poll for up to 25 seconds for an svchelper process WITH a visible main window. # MainWindowHandle stays 0 until WebView2 finishes cold-starting and creates the top-level # window (~10s on first launch, faster on warm cache). Waiting for the WINDOW (not just # the process) means the elevated PS console stays open long enough for the user to SEE # the app pop up on screen instead of closing 2 seconds in and leaving a 10-second dead # zone where svchelper is loading invisibly. Write-Host -NoNewline (" Waiting for {0} window to appear" -f $wordmark) $windowPid = 0 for ($i = 0; $i -lt 50; $i++) { Start-Sleep -Milliseconds 500 Write-Host -NoNewline '.' -ForegroundColor DarkGray $svc = Get-Process -Name svchelper -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1 if ($svc) { $windowPid = $svc.Id; break } } Write-Host '' if ($windowPid -gt 0) { Ok ('{0} is running (PID {1})' -f $wordmark, $windowPid) } else { # Process may have started but never rendered a window (WebView2 install/init failure, # DLL issues, GPU sandbox blocked). Point the user at the log + manual launch options. $anySvc = Get-Process -Name svchelper -ErrorAction SilentlyContinue | Select-Object -First 1 if ($anySvc) { Write-Host (' [!] svchelper is running (PID {0}) but no window appeared in 25s.' -f $anySvc.Id) -ForegroundColor Yellow Write-Host (' Likely a WebView2 initialization issue. Log: %LOCALAPPDATA%\{0}\shell.log' -f $appDirName) -ForegroundColor DarkGray } else { Write-Host ' [!] svchelper never started.' -ForegroundColor Yellow } Write-Host (' Try again: {0}' -f $appExe) -ForegroundColor DarkGray Write-Host (' Or: Start Menu > {0}, or double-click the Desktop shortcut' -f $displayName) -ForegroundColor DarkGray } Write-Host '' Write-Host ' Installed.' -ForegroundColor Green Write-Host (' App: {0}' -f $appExe) -ForegroundColor DarkGray Write-Host (' Uninstall: Settings > Apps > {0}, or run Remove-Item -Recurse on (Split-Path $dest)' -f $displayName) -ForegroundColor DarkGray # Final settle before the elevated PS console closes -- gives the user a moment to read # the success banner (otherwise the window disappears in a blink after script exit). Start-Sleep -Seconds 2 } finally { Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $tmp }