Use marker file instead of task unregister for sync completion
BUILTIN\Users (Limited RunLevel) can't delete scheduled tasks, so Unregister-ScheduledTask failed silently and the sync task kept firing at every logon even after completion. Fix: write C:\Enrollment\sync-complete.txt on completion. At script startup in -AsTask mode, check for the marker and exit immediately if found. The task stays in Task Scheduler but does nothing -- fires at logon, sees marker, exits in under a second. No visible window. Manual sync_intune.bat runs (no -AsTask) ignore the marker and always show the full status display for inventory QR code purposes. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -560,11 +560,16 @@ function Invoke-SetupComplete {
|
||||
Write-Host "The post-reboot DSC install phase is finished. The device is ready."
|
||||
|
||||
if ($AsTask) {
|
||||
# Task mode: unregister our own scheduled task
|
||||
Write-Host "Unregistering sync task..." -ForegroundColor Cyan
|
||||
# Write completion marker so future logon-triggered runs exit
|
||||
# immediately. We can't Unregister-ScheduledTask because the task
|
||||
# runs as BUILTIN\Users (Limited) which lacks permission to delete
|
||||
# tasks. The marker file makes the task a harmless no-op.
|
||||
try {
|
||||
Unregister-ScheduledTask -TaskName 'Shopfloor Intune Sync' -Confirm:$false -ErrorAction SilentlyContinue
|
||||
} catch {}
|
||||
Set-Content -LiteralPath $syncCompleteMarker -Value (Get-Date -Format 'o') -Force
|
||||
Write-Host "Sync complete marker written." -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Warning "Failed to write completion marker: $_"
|
||||
}
|
||||
|
||||
# Machine number prompt only (startup items are auto-applied by
|
||||
# 06-OrganizeDesktop from the PC profile). Tech can re-open
|
||||
@@ -636,6 +641,17 @@ function Invoke-RebootPrompt {
|
||||
# Terminal - neither reliably honors programmatic window resize, so we
|
||||
# solve it by controlling cursor position instead.
|
||||
# ============================================================================
|
||||
$syncCompleteMarker = 'C:\Enrollment\sync-complete.txt'
|
||||
|
||||
# If running as a scheduled task and sync already completed on a prior run,
|
||||
# exit immediately. The task stays registered (BUILTIN\Users can't delete
|
||||
# tasks) but does nothing -- fires at logon, sees marker, exits in <1s.
|
||||
if ($AsTask -and (Test-Path -LiteralPath $syncCompleteMarker)) {
|
||||
Write-Host "Sync already complete (marker exists). Exiting."
|
||||
try { Stop-Transcript | Out-Null } catch {}
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
$qrText = Build-QRCodeText
|
||||
$qrRefreshed = [bool]($qrText -notmatch 'not yet Azure AD joined')
|
||||
|
||||
Reference in New Issue
Block a user