1param([string]$Binary, [switch]$Remove)
2$ErrorActionPreference = 'Stop'
3$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
4$principal = New-Object Security.Principal.WindowsPrincipal($identity)
5if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run this installer as administrator to access the VirtIO serial port.' }
6if ((Get-WmiObject Win32_ComputerSystem).UserName -ne $identity.Name) { throw 'Run this installer from the signed-in administrator account on the VM desktop.' }
7$directory = Join-Path $env:ProgramFiles 'Snowglobe\Guest'
8$destination = Join-Path $directory 'snowglobe-guest.exe'
9$service = New-Object -ComObject Schedule.Service
10$service.Connect()
11$folder = $service.GetFolder('\')
12$name = 'SnowglobeGuest-' + $identity.User.Value
13if ($Remove) {
14 try { $folder.GetTask($name).Stop(0); $folder.DeleteTask($name, 0) } catch { if (Test-Path $destination) { throw } }
15 $used = $false
16 foreach ($task in $folder.GetTasks(1)) {
17 foreach ($action in $task.Definition.Actions) { if ($action.Path -eq $destination) { $used = $true } }
18 }
19 if (!$used -and (Test-Path $destination)) { Remove-Item $destination }
20 return
21}
22if (!$Binary) { throw 'Pass the path to the guest executable with -Binary.' }
23Get-WmiObject Win32_Process -Filter "name='snowglobe-guest.exe'" | Where-Object { $_.ExecutablePath -eq $destination } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
24New-Item -ItemType Directory -Path $directory -Force | Out-Null
25Copy-Item -LiteralPath $Binary -Destination $destination -Force
26$task = $service.NewTask(0)
27$task.Principal.UserId = $identity.User.Value
28$task.Principal.LogonType = 3
29$task.Principal.RunLevel = 1
30$task.Settings.ExecutionTimeLimit = 'PT0S'
31$task.Settings.DisallowStartIfOnBatteries = $false
32$task.Settings.StopIfGoingOnBatteries = $false
33$trigger = $task.Triggers.Create(9)
34$trigger.UserId = $identity.User.Value
35$action = $task.Actions.Create(0)
36$action.Path = $destination
37$registered = $folder.RegisterTaskDefinition($name, $task, 6, $identity.User.Value, $null, 3, $null)
38$registered.Run($null) | Out-Null