Help: How to prevent a Scheduled script to run multiple time in parallel

Hi,

I have a Scheduled Script that collects data for me from Twitter every 5 minutes. Sometimes, that Script can take longer than 5 minutes to do it’s thing or, for whatever reason, its hanging.

So i implemented this:

Get-UAJob -Script $UAScript -Status ‘Running’ | Where StartTime -le (Get-Date).AddMinutes(-5) | Stop-UAJob
If (Get-UAJob -Script $UAScript -Status ‘Running’ | Where Id -ne $UAJobId) {
Write-Warning ‘Job already in progress.’; Exit
}

The idea is to stop any old jobs thats been running for more than 5 minutes, and then check to see if there is still any running (ie: less than 5 minutes).

But i’m getting this error

[8:35:12 AM] [ERR] Call failed with status code 403 (Forbidden): DELETE http://localhost:5000/api/v1/Job/19851
[8:35:13 AM] [WRN] Job already in progress.

How can i get the script to terminate older jobs? Am i missing something? Am i supposed to authenticate somehow?

Okay, so i figured out that the scripts have access to ‘view’ the jobs… but not to stop them.

So adding an AppToken and connecting to UA allowed everything to work!

$apptoken = “eyJhbGciOiJIUzI1NiIsInR5c…ZgQ84”
Connect-UAServer -ComputerName http://localhost:5000 -AppToken $apptoken