Files
hrynco-kswitcher/tools/install-elevated-autostart.ps1

30 lines
2.3 KiB
PowerShell

$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot
$resultPath = Join-Path $root 'build\autostart-install-result.json'
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Administrator approval is required.' }
$exe = Join-Path $root 'build\KSwitcher.exe'
$staged = Join-Path $root 'build\staged\KSwitcher.exe'
$running = @(Get-Process KSwitcher -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $exe })
$exitProcess = Start-Process -FilePath $exe -ArgumentList '--exit' -WindowStyle Hidden -PassThru
if (-not $exitProcess.WaitForExit(5000)) { throw 'KSwitcher exit command timed out.' }
foreach ($process in $running) { if (-not $process.WaitForExit(10000)) { throw 'KSwitcher did not stop; no executable was replaced.' } }
Copy-Item -LiteralPath $exe -Destination (Join-Path $root 'build\staged\KSwitcher.previous.exe') -Force
Copy-Item -LiteralPath $staged -Destination $exe -Force
$helper = Start-Process -FilePath $exe -ArgumentList @('--configure-autostart=2', $identity.User.Value) -WindowStyle Hidden -PassThru
$helper.WaitForExit()
if ($helper.ExitCode -ne 0) { throw 'The native autostart helper failed.' }
$settingsPath = Join-Path $root 'build\data\settings.json'
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
$settings.startWithSystem = $true
$settings | Add-Member -NotePropertyName autostartAsAdministrator -NotePropertyValue $true -Force
[IO.File]::WriteAllText($settingsPath, ($settings | ConvertTo-Json -Depth 12), [Text.UTF8Encoding]::new($false))
Start-ScheduledTask -TaskName 'KSwitcher'
$task = Get-ScheduledTask -TaskName 'KSwitcher'
[pscustomobject]@{success=$true; task=$task.TaskName; runLevel=[string]$task.Principal.RunLevel; logonType=[string]$task.Principal.LogonType; user=$task.Principal.UserId; executable=$task.Actions.Execute; state=[string]$task.State} | ConvertTo-Json | Set-Content -LiteralPath $resultPath -Encoding UTF8
} catch {
[pscustomobject]@{success=$false; error=$_.Exception.Message} | ConvertTo-Json | Set-Content -LiteralPath $resultPath -Encoding UTF8
exit 1
}