foam_sync.ps1 (LIFEBALANCE) 2025-06-19T00:36:31Z

This commit is contained in:
Ben Miller
2025-06-19 00:36:31 -06:00
parent 80a98b4fdd
commit d595694269

View File

@ -33,6 +33,7 @@
# --- Configuration --- # --- Configuration ---
$frequencyMinutes = 2 # How often the Scheduled Task should attempt to run this script $frequencyMinutes = 2 # How often the Scheduled Task should attempt to run this script
$executionTimeLimitBufferSeconds = 30 # Buffer: task stops if it runs longer than (frequency - buffer)
# --- Script Setup --- # --- Script Setup ---
$scriptPath = $MyInvocation.MyCommand.Path $scriptPath = $MyInvocation.MyCommand.Path
@ -85,58 +86,82 @@ $expectedRetrievedActionArgument = "-NoProfile -NonInteractive -ExecutionPolicy
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $actionArgumentForRegistration $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $actionArgumentForRegistration
# Task settings # Task settings
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Hours 1) ` # Calculate a realistic execution time limit based on the frequency
-StopIfGoingOnBatteries:$false # Explicitly ensure it doesn't stop $executionTimeLimitTotalSeconds = ($frequencyMinutes * 60) - $executionTimeLimitBufferSeconds
if ($executionTimeLimitTotalSeconds -lt 30) {
# Ensure a minimum sensible execution time (e.g., 30 seconds)
$executionTimeLimitTotalSeconds = 30
}
$taskExecutionTimeLimit = New-TimeSpan -Seconds $executionTimeLimitTotalSeconds
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $taskExecutionTimeLimit
# Check and configure the scheduled task # Check and configure the scheduled task
try { try {
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
$needsUpdateOrCreation = $true
if ($existingTask) { if ($existingTask) {
Write-Host "Scheduled task '$taskName' already exists. Checking configuration..." Write-Host "Scheduled task '$taskName' already exists. Checking configuration..."
$currentTrigger = $existingTask.Triggers[0] $currentTrigger = $existingTask.Triggers[0]
$currentAction = $existingTask.Actions[0] $currentAction = $existingTask.Actions[0]
# You could also compare $existingTask.Principal.UserId with $taskPrincipal.UserId
# and $existingTask.Description with $taskDescription if strict matching is needed for those.
# Check Trigger # Check Trigger
$triggerMatches = $false $triggerMatches = $false
if ($currentTrigger -is [Microsoft.Management.Infrastructure.CimInstance] ` if ($currentTrigger -is [Microsoft.Management.Infrastructure.CimInstance] `
-and $currentTrigger.RepetitionInterval.TotalMinutes -eq $frequencyMinutes ` -and $currentTrigger.RepetitionInterval.TotalMinutes -eq $frequencyMinutes `
-and $currentTrigger.RepetitionDuration -eq ([TimeSpan]::MaxValue)) { -and $currentTrigger.RepetitionDuration -eq ([TimeSpan]::MaxValue)) {
# Check duration too
$triggerMatches = $true $triggerMatches = $true
} }
# Check Action
$actionMatches = $false $actionMatches = $false
if ($currentAction -is [Microsoft.Management.Infrastructure.CimInstance] ` if ($currentAction -is [Microsoft.Management.Infrastructure.CimInstance] `
-and $currentAction.Execute -eq "powershell.exe" ` -and $currentAction.Execute -eq "powershell.exe" `
-and $currentAction.Argument -eq $expectedRetrievedActionArgument) { # Compare with the expected retrieved format -and $currentAction.Argument -eq $expectedRetrievedActionArgument) {
$actionMatches = $true $actionMatches = $true
} }
if ($triggerMatches -and $actionMatches) { # Check Principal (example, can be expanded)
$principalMatches = ($existingTask.Principal.UserId -eq $taskPrincipal.UserId)
# Check Settings (specifically ExecutionTimeLimit for this change)
$settingsMatch = $false
if ($existingTask.Settings.ExecutionTimeLimit -eq $taskExecutionTimeLimit) {
$settingsMatch = $true
}
if ($triggerMatches -and $actionMatches -and $principalMatches -and $settingsMatch) {
Write-Host "Scheduled task '$taskName' is already correctly configured." Write-Host "Scheduled task '$taskName' is already correctly configured."
$needsUpdateOrCreation = $false
} }
else { else {
Write-Host "Scheduled task '$taskName' configuration differs. It will be updated." Write-Host "Scheduled task '$taskName' configuration differs. Attempting to update in-place..."
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue try {
Set-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $taskPrincipal -Description $taskDescription -ErrorAction Stop
Write-Host "Scheduled task '$taskName' updated successfully."
}
catch {
Write-Warning "Failed to update scheduled task '$taskName' in-place. Error: $($_.Exception.Message)"
Write-Warning "The task remains in its previous state. Manual intervention may be required or re-run with Administrator privileges."
# We intentionally DO NOT unregister here to avoid the scenario you described.
}
} }
} }
else {
if ($needsUpdateOrCreation) { Write-Host "Creating scheduled task '$taskName'..."
if ($existingTask -and -not ($triggerMatches -and $actionMatches)) { try {
Write-Host "Updating scheduled task '$taskName'..." Register-ScheduledTask -TaskName $taskName -Description $taskDescription -Principal $taskPrincipal -Trigger $trigger -Action $action -Settings $settings -ErrorAction Stop
Write-Host "Scheduled task '$taskName' created successfully."
} }
else { catch {
Write-Host "Creating scheduled task '$taskName'..." Write-Warning "Failed to create scheduled task '$taskName'. Error: $($_.Exception.Message)"
Write-Warning "You may need to run this script as Administrator."
} }
Register-ScheduledTask -TaskName $taskName -Description $taskDescription -Principal $taskPrincipal -Trigger $trigger -Action $action -Settings $settings -ErrorAction Stop
Write-Host "Scheduled task '$taskName' registered/updated successfully."
} }
} }
catch { catch {
Write-Warning "Failed to register or update scheduled task '$taskName'. Error: $($_.Exception.Message)" # This outer catch is for unexpected errors, e.g., if Get-ScheduledTask had -ErrorAction Stop
Write-Warning "You may need to run this script as Administrator once to register the scheduled task." Write-Warning "An unexpected error occurred during scheduled task setup for '$taskName'. Error: $($_.Exception.Message)"
} }
# --- Git Operations --- # --- Git Operations ---