Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 96 additions & 14 deletions ee/maintained-apps/inputs/winget/scripts/devtoys_install.ps1
Original file line number Diff line number Diff line change
@@ -1,30 +1,112 @@
# Learn more about .exe install scripts:
# http://fleetdm.com/learn-more-about/exe-install-scripts
#
# This app ships as an Inno Setup installer.
# DevToys ships as an Inno Setup installer whose install directory is
# {userpf}\DevToys Preview, so it installs per user and has no machine-wide
# mode. Installing it from this script's SYSTEM context would put it in
# SYSTEM's profile where nobody can launch it. Run the installer as the
# signed-in user instead.

$exeFilePath = "${env:INSTALLER_PATH}"
$taskName = "fleet-install-devtoys"
$taskRunning = 267009 # SCHED_S_TASK_RUNNING
$exitCode = 0
$stageDir = $null

try {
if (-not (Test-Path $exeFilePath)) {
Write-Host "Error: Installer file not found at: $exeFilePath"
Exit 1
$owner = Get-CimInstance Win32_Process -Filter 'name = "explorer.exe"' -ErrorAction SilentlyContinue |
Invoke-CimMethod -MethodName GetOwner -ErrorAction SilentlyContinue |
Where-Object { $_.User } |
Select-Object -First 1
if (-not $owner) {
Throw "DevToys installs per user and no user is signed in to this host. Sign in and try again."
}
$userAccount = "$($owner.Domain)\$($owner.User)"
$sid = (New-Object System.Security.Principal.NTAccount($userAccount)).Translate(
[System.Security.Principal.SecurityIdentifier]).Value
Write-Host "Installing DevToys for $userAccount."

$processOptions = @{
FilePath = "$exeFilePath"
ArgumentList = "/VERYSILENT /SUPPRESSMSGBOXES /NORESTART"
PassThru = $true
Wait = $true
NoNewWindow = $true
# Setup can't close a running DevToys from the scheduled task's logon session,
# so it would wait on a "files in use" prompt until this script times out.
# Stop what's running from the user's install first.
$profilePath = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid" -ErrorAction SilentlyContinue).ProfileImagePath
if ($profilePath) {
$appDir = Join-Path $profilePath "AppData\Local\Programs\DevToys Preview"
$isAppProcess = { $_.Path -and $_.Path.StartsWith("$appDir\", [System.StringComparison]::OrdinalIgnoreCase) }
$running = @(Get-Process -ErrorAction SilentlyContinue | Where-Object $isAppProcess)
if ($running.Count) {
Write-Host "Stopping DevToys: $(($running | ForEach-Object { "$($_.Name) ($($_.Id))" }) -join ', ')"
# Windows reuses PIDs, so match the start time too.
$stopped = @($running | ForEach-Object { "$($_.Id)|$($_.StartTime.Ticks)" })
$running | Stop-Process -Force -ErrorAction SilentlyContinue
for ($waited = 0; $waited -lt 30; $waited++) {
Start-Sleep -Seconds 1
$running = @(Get-Process -ErrorAction SilentlyContinue | Where-Object $isAppProcess |
Where-Object { $stopped -contains "$($_.Id)|$($_.StartTime.Ticks)" })
if ($running.Count -eq 0) { break }
}
if ($running.Count) {
Throw "DevToys is still running ($(($running | ForEach-Object { "$($_.Name) ($($_.Id))" }) -join ', ')) and Setup can't replace it. Quit it and try again."
}
}
}

$process = Start-Process @processOptions
$exitCode = $process.ExitCode
# Fleet's installer directory is not readable by that user, so stage a copy in
# a new folder only SYSTEM and Administrators can write to.
$security = New-Object System.Security.AccessControl.DirectorySecurity
$security.SetAccessRuleProtection($true, $false)
foreach ($grant in @(@("S-1-5-18", "FullControl"), @("S-1-5-32-544", "FullControl"), @($sid, "ReadAndExecute"))) {
$security.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
(New-Object System.Security.Principal.SecurityIdentifier($grant[0])), $grant[1],
"ContainerInherit, ObjectInherit", "None", "Allow")))
}
$stageDir = Join-Path $env:ProgramData ("fleet-devtoys-" + [guid]::NewGuid().ToString("N"))
[void][System.IO.Directory]::CreateDirectory($stageDir, $security)
$stagedInstaller = Join-Path $stageDir (Split-Path $exeFilePath -Leaf)
Copy-Item -LiteralPath $exeFilePath -Destination $stagedInstaller -Force -ErrorAction Stop

# Inno Setup: /VERYSILENT runs without any UI (the NSIS /S switch does nothing).
$action = New-ScheduledTaskAction -Execute $stagedInstaller -Argument "/VERYSILENT /SUPPRESSMSGBOXES /NORESTART"
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$principal = New-ScheduledTaskPrincipal -UserId $userAccount
$task = New-ScheduledTask -Action $action -Settings $settings -Principal $principal
Register-ScheduledTask -TaskName $taskName -InputObject $task -Force -ErrorAction Stop | Out-Null

$startDate = Get-Date
$lastRun = (Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction Stop).LastRunTime
Start-ScheduledTask -TaskName $taskName -ErrorAction Stop

# Wait for a result rather than for the "Running" state, which a fast task can
# enter and leave between polls. A task that's still queued hasn't updated
# LastRunTime yet.
Start-Sleep -Seconds 2
while ($true) {
$info = Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction Stop
$state = (Get-ScheduledTask -TaskName $taskName -ErrorAction Stop).State
if ($info.LastRunTime -ne $lastRun -and $state -ne "Running" -and $info.LastTaskResult -ne $taskRunning) {
$exitCode = $info.LastTaskResult
break
}
if ((New-TimeSpan -Start $startDate).TotalSeconds -gt 900) {
Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
Throw "Timed out waiting for the install task to finish."
}
Start-Sleep -Seconds 5
}
Write-Host "Install exit code: $exitCode"
Exit $exitCode

} catch {
Write-Host "Error: $_"
Exit 1
$exitCode = 1
} finally {
if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
if ($stageDir -and (Test-Path -LiteralPath $stageDir)) {
Remove-Item -LiteralPath $stageDir -Recurse -Force -ErrorAction SilentlyContinue
}
}

# Exit turns a code above Int32.MaxValue, such as a task's HRESULT, into 0.
if ($exitCode -gt [int]::MaxValue) { $exitCode = 1 }
Exit $exitCode
Loading
Loading