I have a Powershell script to add a new schedule task. It's used to launch a PS1 file which includes some SQL querying on both local SQL box and remote SQL boxes.
If this script creates the schedule, I have to make one change manually for it to work: I have to set the option "Run whether user is logged on or not".
Here is the function:
function createschedule {
$startdatetime = (get-date).AddMinutes(1).ToString("HH:mm")
$taskName = "My Bestest Schedule"
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-file "C:\mypath\bin\mypowershellscript.ps1"'
$trigger = New-ScheduledTaskTrigger -Once -At $startdatetime
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable
echo ""
echo "Adding Basic parameterized task..."
Register-ScheduledTask -TaskName $taskName -Trigger $trigger -Action $action -Setting $settings -User "Administrator" -description "Sitewatch v2 Collector" -RunLevel 1 | Out-null
$trigger.RepetitionInterval = (New-TimeSpan -Minutes 1)
$trigger.RepetitionDuration = (New-TimeSpan -Days 1000)
echo "Adding trigger to the new task..."
Set-ScheduledTask $taskName -Trigger $trigger | Out-Null
echo ""
}
When the script creates the entry, the command runs and pops up a window for a few seconds. It still works, but only if logged in. If I switch the setting manually, it works fine logged out.
Things I've tried/considered:
- changed the user to NETWORKSERVICE, or SYSTEM but those cannot authenticate with SQL when doing the querying
- There is a switch I found
-logontype ServiceAccount
but that doesn't seem to work - I tried using the 'Principal' portion:
#$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators"
but that gives errors too - Lastly, I cannot simply supply the password because this will be run on different boxes that have different passwords for Administrator (or whatever admin use I set)
Looking at this post, I couldn't determine what I needed: How to set schedule.service "Run whether user is logged on or not" in Powershell?
Also, Microsoft appears to say that simply having a Principal, it enables a task to run whether the user is logged in or not but it doesn't work for me:
Detailed Description The New-ScheduledTaskPrincipal cmdlet creates an object that contains a scheduled task principal. Use a scheduled task principal to run a task under the security context of a specified account. When you use a scheduled task principal, Task Scheduler can run the task regardless of whether that account is logged on.
Found here: https://technet.microsoft.com/en-us/library/jj649825.aspx
Thx.