Files
screenjob/install_backend_service.ps1
2026-05-31 20:43:36 +02:00

85 lines
3.0 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess = $true)]
param(
[switch]$Remove,
[switch]$AllUsers,
[switch]$StartNow
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $PSCommandPath
$backendScript = Join-Path $scriptDir "start_backend.ps1"
$vbsLauncher = Join-Path $scriptDir "start_backend_hidden.vbs"
$shortcutName = "ScreenJob Backend.lnk"
if (-not (Test-Path -LiteralPath $backendScript)) {
throw "Backend launcher script not found: $backendScript"
}
if (-not (Test-Path -LiteralPath $vbsLauncher)) {
throw "Hidden backend launcher file not found: $vbsLauncher"
}
function Test-IsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
$legacyService = Get-Service -Name "ScreenJobBackend" -ErrorAction SilentlyContinue
if ($null -ne $legacyService) {
if (Test-IsAdministrator) {
if ($PSCmdlet.ShouldProcess("ScreenJobBackend", "Remove legacy Windows service")) {
if ($legacyService.Status -ne "Stopped") {
Stop-Service -Name "ScreenJobBackend" -Force -ErrorAction Stop
}
& sc.exe delete ScreenJobBackend | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Failed to delete legacy service 'ScreenJobBackend' (sc.exe exit code $LASTEXITCODE)."
}
Write-Host "Removed legacy Windows service: ScreenJobBackend"
}
} else {
Write-Warning "Legacy Windows service 'ScreenJobBackend' is still installed. Run uninstall_backend_service.ps1 from an elevated PowerShell session once to remove it."
}
}
$startupFolder = if ($AllUsers) {
[Environment]::GetFolderPath("CommonStartup")
} else {
[Environment]::GetFolderPath("Startup")
}
$shortcutPath = Join-Path $startupFolder $shortcutName
if ($Remove) {
if (Test-Path -LiteralPath $shortcutPath) {
if ($PSCmdlet.ShouldProcess($shortcutPath, "Remove backend startup shortcut")) {
Remove-Item -LiteralPath $shortcutPath -Force
Write-Host "Removed backend startup shortcut: $shortcutPath"
}
} else {
Write-Host "No backend startup shortcut found at: $shortcutPath"
}
return
}
if ($PSCmdlet.ShouldProcess($shortcutPath, "Create backend startup shortcut")) {
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = "$env:SystemRoot\System32\wscript.exe"
$shortcut.Arguments = '"' + $vbsLauncher + '"'
$shortcut.WorkingDirectory = $scriptDir
$shortcut.Description = "Launch ScreenJob backend at sign-in in the current user session."
$shortcut.Save()
Write-Host "Created backend startup shortcut: $shortcutPath"
}
if ($StartNow) {
Start-Process -FilePath "$env:SystemRoot\System32\wscript.exe" -ArgumentList @($vbsLauncher) -WorkingDirectory $scriptDir | Out-Null
Write-Host "Started backend launcher now."
}