diff --git a/ci/agent-service-standard-user-probe.ps1 b/ci/agent-service-standard-user-probe.ps1 index f1876fb64..bda3a2c07 100644 --- a/ci/agent-service-standard-user-probe.ps1 +++ b/ci/agent-service-standard-user-probe.ps1 @@ -505,7 +505,23 @@ function Invoke-ServiceProbe { $account.Password.Dispose() } try { - if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop } + if (Test-Path -LiteralPath $root) { + # The service creates directories, such as config\identity, that only LocalSystem may access. + # Whether one exists by now depends on how far the service got. + # What the runner account cannot remove is therefore removed as LocalSystem, as the job's other cleanups do. + # UNTESTED: no run is sure to leave such a directory, so passing runs may never reach the LocalSystem removal. + # When changing it, run the probe with a LocalSystem-only tree under the config directory and check that cleanup removes it. + try { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop + } catch { + $accountError = $_ + $systemOutput = & psexec.exe -accepteula -nobanner -s cmd.exe /d /c rd /s /q "$root" 2>&1 + if (Test-Path -LiteralPath $root) { + throw "$accountError; removing it as LocalSystem also failed with exit code ${LASTEXITCODE}: $($systemOutput -join ' ')" + } + $global:LASTEXITCODE = 0 + } + } } catch { $cleanupErrors.Add("Directory cleanup failed: $_") }